Can we really declare Parametrized ViewModel instance as BindingContext in XAML?
Can we really declare Parametrized ViewModel instance as BindingContext in XAML?
In Xamarin.Forms, it is not straightforward to declare a parameterized ViewModel instance as the BindingContext directly in XAML. The typical approach to setting the BindingContext with a ViewModel that requires parameters is to do so in the code-behind of the XAML page. Here are some key points and methods to handle this scenario:
The most common method is to instantiate the ViewModel with parameters in the code-behind and then set it as the BindingContext:
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
var myViewModel = new MyViewModel(param1, param2);
BindingContext = myViewModel;
}
}
Another approach is to use a ViewModel Locator pattern, which can provide instances of ViewModels, including those with parameters:
public static class ViewModelLocator
{
public static MyViewModel MyViewModel => new MyViewModel(param1, param2);
}
In XAML, you can then bind to this static property:
<ContentPage xmlns:local="clr-namespace:MyApp;assembly=MyApp"
BindingContext="{x:Static local:ViewModelLocator.MyViewModel}">
<!-- Page content -->
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.