开发者

WPF Commands - Doing it with no code-behind

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 开发者_Python百科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);
}


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.


If you're specifically looking at trying to bind a command in the ViewModel to one of the application commands in XAML, you have to build the infrastructure to do so yourself. I walk though doing that in this answer which then allows you to do something like this:

<local:RoutedCommandHandlers.Commands>
  <local:RoutedCommandHandler RoutedCommand="ApplicationCommands.Save" 
                              Command="{Binding TheSaveCommand}" />
</local:RoutedCommandHandlers.Commands>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜