views:

444

answers:

1

I'm building a simple data entry app in WPF form using the MVVM pattern. Each form has a presenter object that exposes all the data etc. I'd like to use WPF Commands for enabling and disabling Edit/Save/Delete buttons and menu options.

My problem is that this approach seems to require me to add lots of code to the code-behind. I'm trying to keep my presentation layer as thin as possible so I'd much rather this code/logic was inside my presenter (or ViewModel) class rather than in code-behind. Can anyone suggest a way to achieve the same thing without code-behind?

My XAML looks a bit like this:

<Window.CommandBindings>
    <CommandBinding 
        Command="ApplicationCommands.Save"
        CanExecute="CommandBinding_CanExecute"
        Executed="CommandBinding_Executed"
    />
</Window.CommandBindings>

and my code-behind looks a bit like this:

private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = (
        _presenter.SelectedStore != null &&
        _presenter.SelectedStore.IsValid);
}
+9  A: 

The Model-View-ViewModel (MVVM) design pattern aims at achieving exactly that goal, and Josh Smith's excellent article explains how to apply it.

For commands you can use the RelayCommand class described in the article.

Since you already have a presenter object, you can let that class expose an ICommand property that implements the desired logic, and then bind the XAML to that command. It's all explained in the article.

Mark Seemann
Great link - cheers!
Phil Jenkins