In trying to follow MVVM with WPF I ran across a case where I am not sure where to put code for testing. All lines in the btnReset_Click Method UI commands so I don’t know if they belong in the view model but I also don’t want to put code in my code behind. I have listed out two options I have thought of but am also open to another solution as well.
Public class Main : Window
{
private void btnReset_Click(object sender, RoutedEventArgs e)
{
DynamicStackPanel.Children.Clear();
controls.Clear();
txtUsername.Text = string.Empty;
txtPassword.Text = string.Empty;
txtResponse.Text = string.Empty;
cbxTestEnvironment.SelectedValue = string.Empty;
cbxOperation.SelectedItem = null;
cbxTestEnvironment.SelectedItem = null;
}
}
or
public class MainViewModel : DependencyObject
{
public MainViewModel : DependancyObject
{
public MainViewModel(UtilityMain win)
{
win.btnReset.Click +=btnReset_Click;
}
private void btnReset_Click(object sender, RoutedEventArgs e)
{
DynamicStackPanel.Children.Clear();
controls.Clear();
txtUsername.Text = string.Empty;
txtPassword.Text = string.Empty;
txtResponse.Text = string.Empty;
cbxTestEnvironment.SelectedValue = string.Empty;
cbxOperation.SelectedItem = null;
cbxTestEnvironment.SelectedItem = null;
}
}
This is not really an MVVM approach. The view model should not contain any references to the view however it should represent the the views logic. Likewise the view should contain as little view logic as possible. You should be able to achieve this separation by using a combination of data and command binding. Bind controls in your view to data properties of the view model. Bind to commands on the view model from the view to invoke view logic. The view model operates on the data not UI controls. The ui controls are updated from the view model via data binding. The whole point is to separate your UI controls from your view logic.