I was talking to someone today about picking a design pattern for how to handle logic in their WPF program and hoping that the SO community can help with further advice to make the decision easier. What factors in favour of commands outweigh the inconvenience?
I prepared a full sample along with some UML diagrams of the first two of three approaches:
- Use Click event handlers on buttons and menus.
- Use commands bound in XAML.
- Use commands bound in code, with the XAML kept for pure GUI layout and styling.
The introductory course he'd been on and many of the books show simple Click event handlers as the natural way to connect logic to UI objects.
He was a bit stunned by the amount of overhead required to use commands with both the command being created in the code behind file:
public static readonly ICommand cmdShow2 = new RoutedUICommand(
"Show Window2", "cmdShow2",
typeof(TestDespatchWindow));
and then even more code in the XAML with the wordy way the command has to be identified and bound:
<Window x:Class="WPFDispatchDemo.TestDespatchWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:w="clr-namespace:WPFDispatchDemo"..>
<Window.CommandBindings>
<CommandBinding Command="{x:Static w:TestDespatchWindow.cmdShow2}"
Executed="OnShow2" />
</Window.CommandBindings>
<DockPanel>
<StackPanel Margin="0,8,0,0">
<Button x:Name="Show2EventBased"
Margin="10,2,10,2"
Click="OnShow2"
Content="Show2 via WPF Event"/>
<Button x:Name="Show2Command"
Command="{x:Static w:TestDespatchWindow.cmdShow2}"
Margin="10,2,10,2"
Content="Show2 via WPF"/>
</StackPanel>
</DockPanel>
</Window>
I can't (yet) claim to be a WPF expert so I may have painted things as more complex than they really are but my suspicion is that you can't simplify things much more than the above.
Edit:
I found an interesting 3-way comparison between DelegateCommand, RoutedCommand and Event.