Friday, August 29, 2014

Setting the DataContext of a View to a ViewModel in MVVM

Setting the DataContext of a View to a ViewModel can be done in various ways. It can be done in the constructor of the View
public LoginView()
{
 InitializeComponent();
 DataContext = new LoginViewModel();
}
or
public LoginView(LoginViewModel viewModel)
{
 InitializeComponent();
 DataContext = viewModel;
}
or directly in the XAML
<UserControl x:Class="MvvmPassword.LoginView"
      x:Name="This"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:MvvmPassword">
    <UserControl.Resources>
        <local:LoginViewModel x:Key="ViewModel" />
    </UserControl.Resources>
    <Grid DataContext="{Binding Source={StaticResource ViewModel}}"> 
        ... 
    </Grid>
</UserControl>
or
<UserControl x:Class="MvvmPassword.LoginView"
      x:Name="This"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="clr-namespace:MvvmPassword"> 
 <UserControl.DataContext>
  <local:LoginViewModel x:Name="ViewModel" />
 </UserControl.DataContext>
 <Grid> 
           ...
        </Grid>
</UserControl>

1 comment:

  1. This only works if you have a default parameter-less constructor.

    ReplyDelete