Is there any benefit in binding a ViewModel in backend .cs file?

Technology CommunityCategory: XamarinIs there any benefit in binding a ViewModel in backend .cs file?
VietMX Staff asked 3 years ago

Yes, we can customize the ViewModel initialization in the XAML’s backend .cs file. Suppose, we want to initialize it with some dynamic data. So if your page requires some dynamic data passed into the page before it gets loaded, you need to pass it into ViewModel‘s parameterized constructor. Now assign this instance of ViewModel to the BindingContext of a Page in the backend .cs file. Thus, it helps us in constructing the ViewModel with some data.

public partial class HomePage : ContentPage
{ 
    public HomePage(int userId) 
    { 
        //Ex. I want to pass the logged in user id into HomeViewModel then, 

        BindingContext = new HomeViewModel(userId); 
        InitializeComponent(); 
    } 
}