Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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);
}
like image 204
Steve Avatar asked Oct 09 '09 08:10

Steve


People also ask

How to implement commands in WPF?

Commands in WPF are created by implementing the ICommand interface. ICommand exposes two methods, Execute, and CanExecute, and an event, CanExecuteChanged. Execute performs the actions that are associated with the command. CanExecute determines whether the command can execute on the current command target.

What is code behind in WPF?

Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in XAML.

How to use command binding in WPF?

Bind the command in the HierarchyNavigator control. To do this, create a new instance of the ViewModel sample class and set DataContext for the parent StackPanel. This will reflect changes in the children. Whenever the selected item changes, the TextBox Text value will change.

What is command in WPF with example?

Commands provide a mechanism for the view to update the model in the MVVM architecture. Commands provide a way to search the element tree for a command handler. The ICommand interface is defined inside the System. Windows.


1 Answers

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.

like image 167
Mark Seemann Avatar answered Nov 15 '22 07:11

Mark Seemann