Can we really declare Parametrized ViewModel instance as BindingContext in XAML?

Technology CommunityCategory: XamarinCan we really declare Parametrized ViewModel instance as BindingContext in XAML?
VietMX Staff asked 3 years ago

Yes, but we can pass static values only. We can use x:Arguments attribute. Example:

<ContentPage.BindingContext>
    <vm:HomeViewModel>
        <x:Arguments>
            <x:Int32 >1234</x:Int32> //This is passed as a static value as an argument 
                                     //to the parametrized construction of ViewModel in XAML.
        </x:Arguments>
    </vm:HomeViewModel>
</ContentPage.BindingContext>

public class HomeViewModel : BaseViewModel
{
    //Parametrized initialization of viewmodel
    public HomeViewModel(int employeeId)
    {
         //Here you will get 1234 value in the employeeId parameter.
    }
}

This requires that the ViewModel constructor parameters matches with the Type and number of arguments provided in XAML.