I'm developing a WPF application using Mahapps.Metro, a Nuget package that provides "modern" UI styling.
I have created a dialog that is one of those selection dialogs where you select an item on the left hand side, click the right arrow button, and the item moves to the right hand side.
One of the validation rules in my dialog is that at least one item has to be selected before you push the button, so (in the Code Behind of my view) I open a message box and notify the user if he doesn't select at least one item:
private void AddButton_Click(object sender, RoutedEventArgs e)
{
if (!IsAnySelected(Users))
{
// MetroWindow call
this.ShowMessageAsync("Permissions", "Please select a User.");
return;
// Call ViewModel `AddPermissions()` method here.
}
}
bool IsAnySelected(DataGrid dataGrid)
{
foreach(dynamic d in dataGrid.ItemsSource)
{
if (d.IsSelected) return true;
}
return false;
}
(The DataGrid
is bound to an ObservableCollection
in the ViewModel)
Because ordinary message boxes in WPF are not stylable, Mahapps provides its own. It was here that I discovered that MahApps throws a null reference exception when I try to open a message box in my View. It has something to do with my setup, because their demo works just fine.
It turns out that someone provided a way to open a Mahapps message box in the View Model instead of the view. My question is, why would you want to do this?
Doesn't the View own responsibility for any visual elements (including message boxes), and isn't validation the one thing that's permissible to do in the View's Code Behind?
Note that this approach causes a new wrinkle, which is that you now need a way to fire the View Model's method or ICommand from CodeBehind:
(DataContext as SecurityDialogViewModel).AddPermissions();