According to the MVVM pattern:
- The View knows about the ViewModel - it will have a reference to it either as a concrete instance or an interface
- The ViewModel should not know about the view at all.
If you need to handle events, then there are two ways which I know of to do it:
1: Expose a command in your viewmodel, and use databinding to trigger it. This is my preferred way, eg:
class MyViewModel
{
public ICommand ClickCommand { get; set; }
}
<Button Command="{Binding Path=ClickCommand}" />
If you do this then you can test the command by simply calling myViewModel.ClickCommand.Execute
manually.
2: Expose a function in the viewmodel, and write the absolute minimum in the .xaml.cs
file to handle the event and call the function, eg:
class MyViewModel
{
public void HandleClick(){ }
}
<Button Click="MyClickHandler">
//.xaml.cs file
public void MyClickHandler( Object sender, EventArgs e ) {
m_viewModel.HandleClick()
}
If you do this, then you can test by simply calling myViewModel.HandleClick
manually. You shouldn't need to bother with unit testing the MyClickHandler
code as it's only 1 line!