WPF Architecture Confusion RE: Routed Commands, Events, and Gestures - wpf

In learning WPF, I've been reading scads of books and web sites. One thing that seems to keep evading me is how we are supposed to properly wire up RoutedCommands. In one article, the author pointed out that the codebehind for your XAML files is supposed to contain nothing more than the call to InitializeComponent. I can get behind that. It makes the XAML file nothing more than a presentation document, and satisifies my unholy craving for separation of concerns.
On the other hand, every sample I've seen that addresses double-click events seems to want you to write code. It was my understanding that we wanted to get away from having repetitive code in the codebehind files (and, again, I'm all for that), so it seems to me that that's not the right way to do it. The same is true of menu commands, toolbar button clicks, and so forth.
Imagine, for instance, that I have a command to open a document. That command has to present the Open dialog, then open the document and cache it in the application state. (This application only allows you to work on one document at a time.) The user can invoke this command by either:
Choosing File->Open from the menu.
Typing Ctrl+O.
Clicking the Open button on the toolbar.
If I trust most of the sources on the Web, I have to write at least two Click event handlers that then invoke the command, polluting the codebehind file. That seems, to me, to defeat the purpose of having the Commands. I thought that I read somewhere that there was a way to bind the command to these things declaratively in XAML and it would do it for you, even disabling the command if it couldn't execute. But now I can't seem to find it, nor a decent example of how to do it.
Could someone please explain this to me? It's all starting to look like voodoo and shrapnel at this point.

The usual way to avoid codebehind with commands is to avoid RoutedCommands. In the various variations on the MVVM (Model-View-ViewModel) theme, people tend to use custom implementations of ICommand. They write a ViewModel class that is placed in the DataContext of the UI. This ViewModel exposes properties of type ICommand, and those command properties are connected to menu items, buttons and so on through data binding. (And it's usually just the one implementation of ICommand used over and over again - search the web for either RelayCommand or DelegateCommand or DelegatingCommand, and you'll see the pattern - it's basically ICommand as a wrapper around a delegate, with optional support for enabled/disabled.)
In this idiom, you almost never use the built-in commands like ApplicationCommands.Open. The only real use for those things is if you want focus-sensitive commands to be handled intrinsically by controls. E.g., the TextBox has built in command handling for Edit, Copy, Paste, and so on. This avoids the codebehind issue because it's a full custom control, and custom controls don't really have codebehind as such - they're all code. (The Xaml is actually in a completely separate object, the Template, and isn't really part of the control.) And in any case, it's not your code - you have a control that already knows how to support the command, so you can keep entirely within the Xaml here.
Command routing is interesting in that particular scenario because it lets you put one set of menu items associated with the various editing controls, and the routing system figures out which textbox (or whatever) will handle the command based on where the focus is. If that's not what you want, command routing probably isn't much use to you.
However, there's a bigger issue here of what to do when you find that you really do have to put code in the codebehind. Commands usually aren't an example of that scenario if you use custom ICommand implementations (although there's the odd exception), but the slightly more interesting user input events are. You mention double click, but also, if you're doing any kind of unusual interactivity you tend to want things like mouse up/down and so on.
In this case, the usual approach is to bite the bullet and put code in the codebehind, but you try to keep it to one line per event handler. Basically, your codebehind just calls into the relevant method on the viewmodel, and that's what really handles the event.
The lovely thing about that is it makes it really easy to write automated tests. Want to simulate the mouse entering a particular part of your UI? No need to mess around with unit test UI automation frameworks - just call the relevant method directly!

Commanding in WPF is quite cumbersome, but it does solve the problem of updating IsEnabled for you. Here's the canonical example. Step 1 is optional because there are a lot of built-in common commands to reduce the amount of boiler-plate.
Step 1. (Optional) Create your command in a static class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication1
{
public static class Commands
{
public static RoutedCommand WibbleCommand = new RoutedUICommand
(
"Wibble",
"Wibble",
typeof(Commands),
new InputGestureCollection()
{
new KeyGesture(Key.O, ModifierKeys.Control)
}
);
}
}
Step 2: Declare command bindings in the xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
<CommandBinding
Command="{x:Static local:Commands.WibbleCommand}"
Executed="WibbleCommandExecuted"
CanExecute="WibbleCommandCanExecute"
/>
</Window.CommandBindings>
Step 3: Wire up your controls (menuitems, buttons etc)
The long binding here is to rectify the fact that Button by default won't use the command text.
<Button Command="{x:Static local:Commands.WibbleCommand}" Width="200" Height="80">
<TextBlock Text="{Binding Path=Command.Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
</TextBlock>
</Button>
Step 4: Implement handlers for Execute and CanExecute in codebehind
Careful with CanExecute! This will be called quite often, so try not to do anything expensive here.
private void WibbleCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Wibbled!");
}
private void WibbleCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = DateTime.Now.Minute % 2 == 0;
}

Related

XAML minimize/maximize/close buttons through SystemCommands

There's a WPF class called SystemCommands. I've seen examples of these commands being used on buttons to perform common window tasks like maximize, minimize and close.
One of the examples I found looked like this (simplified):
<Window x:Name="MainWindow">
<Grid>
<Button Content="Close"
Command="{x:Static SystemCommands.CloseWindowCommand}"
CommandParameter="{Binding ElementName=MainWindow}" />
</Grid>
</Window>
When I start the application the button is disabled and I can't click it. Changing the IsEnabled property has no effect.
I managed to get the button to be enabled once, but I'm not able to reproduce it now. In any case, when it was enabled, nothing happened when I clicked it.
What must I do to get this button enabled and to actually close the window (or minimize/maximize)? I would really prefer it to be a XAML only solution if this is possible.
These are only predefined RoutedCommand(s) without any implementation. You must provide the implementation by yourself.
https://msdn.microsoft.com/en-us/library/system.windows.systemcommands
The commands in the SystemCommands class represent a set of common
commands that manage a Window. The properties in this class represent
RoutedCommand objects and do not provide the implementation logic for
the command. You can provide the logic for a command by binding the
command with a CommandBinding. Alternatively, the SystemCommands class provides static methods that implement the logic for the specified Window. You can pass a static method to a type that implements ICommand and that accepts a delegate. For more information, see the example in the InputBinding class.

ViewModel Handling Events

I saw an question here where OP asked about binding events to ViewModel. Basically ViewModel shall respresent an abstract View containing necessary data from Model so that the View may be also able to use Bindings. But to be able to fullfill all that the ViewModel must also conver most of the use cases which are happening in the View such as example if search textbox is empty the search button shall be greyed out. That works fine but lets add events to the game. It would be way easier if Button.Click where bindable to an EventHandler in ViewModel and inside the event handler you would be then able to use model objects.
Now my question is since WPF supports event driven programming why cant events be handled in ViewModel? How could I provide binding events funcionality?
Event handlers would sit in the view's code behind file. If you're using MVVM, then you'll want to minimise the amount of code in a code behind file.
WPF supports commanding, and the ICommand interface includes a CanExecute and Execute method. There are implementations of ICommand which allow these methods to be implemented on the view model.
Having said that, commanding also has its limitations, so you should consider using an MVVM framework when using MVVM. Something like Caliburn.Micro comes with Actions which also allow verbs on the view model to be invoked based on control events.
It is because the use of event explicitly breaks the MVVM pattern (as I am sure you are aware). However there is another way around this - by using the Attached Command Behaviour pattern. More information here.
Code for a small but great framework for attached commands is downloadable from here.
I hope this helps.
Edit. attached behaviour allow you to use events without breaking the MVVM pattern. The use is like
<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2" x:Name="test">
<local:CommandBehaviorCollection.Behaviors>
<local:BehaviorBinding Event="MouseLeftButtonDown"
Action="{Binding DoSomething}"
CommandParameter="An Action on MouseLeftButtonDown"/>
<local:BehaviorBinding Event="MouseRightButtonDown"
Command="{Binding SomeCommand}"
CommandParameter="A Command on MouseRightButtonDown"/>
</local:CommandBehaviorCollection.Behaviors>
<TextBlock Text="MouseDown on this border to execute the command"/>
</Border>

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);
}
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>

XAML without the .xaml.cs code behind files

I'm using WPF with the Model-View-ViewModel pattern. Thus, my code behind files (.xaml.cs) are all empty, except for the constructor with a call to InitializeComponent. Thus, for every .xaml file I have a matching, useless, .xaml.cs file.
I swear I read somewhere that if the code behind file is empty except for the constructor, there is a way to delete the file from the project altogether. After searching the net, it seems that the appropriate way to do this is to use the 'x:Subclass' attribute:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
x:Class="MyNamespace.MyClass"
x:Subclass="UserControl"
d:DesignWidth="700" d:DesignHeight="500">
This does the following in the generated .g.cs file:
Removes the 'partial' class modifier on MyClass.
Adds the class 'UserControl' in to its subclass list.
Seems perfect. Indeed, if you still have the .xaml.cs file in the build, it no longer compiles because of the missing partial--so I'm thinking this must be correct. However, if I remove the superfluous file from the build and run, the control does not get initialized correctly (it is blank). This is, I presume, because InitializeComponent() is not getting called. I see InitializeComponent is not virtual, so it seems there would be no way for the base class to call it (short of using reflection).
Am I missing something?
Thanks!
Eric
As another option, if you don't want to go all the way to using DataTemplates, here is an alternate approach for UserControls:
Use the x:Code attribute to embed the constructor call in the XAML:
<x:Code><![CDATA[ public MyClass() { InitializeComponent(); }]]></x:Code>
Eric
If you follow Josh Smith's MVVM article, he uses DataTemplates for Views rather than user controls. If you put your DataTemplates into ResourceDictionaries, they don't have a code-behind at all. If you're not using the code-behind of your user control, doesn't that mean you could use a DataTemplate approach? If you do that, WPF will take care of binding your View to your ViewModel for you.
I had a discussion with a Windows Client team member at PDC about this, and right now, was told that there is no officially supported way to completely eliminate the code behind file. As you can see, you can get it to compile, but InitializeComponent() is never called, so the control doesn't get setup properly.
The x:Subclass attribute "usage is primarily intended for languages that do not support partial class declarations." It was not intended to allow this behavior (unfortunately).
If you are using caliburn micro you can effectively remove .xaml.cs, the framework takes care of initialization (i.e. if you are going with the view-model approach).
This is discussed https://caliburnmicro.codeplex.com/discussions/444250
Out of sheer curiosity, have you tried using this:
x:Subclass="Control"
By default, UserControls require the InitializeComponent() call, but defacto-standard Controls do not. I'd be interested to see if this works.
-Doug

WPF using custom RoutedUICommands or simple event handlers?

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.
Commands their advantages and disadvantages, you have to choose based on your situation,
I highly recommend you make that choice on a case basis, don't choose "the one true way" for the entire project.
For some cases the separation between sender and receiver and the ability to send commands using only XAML is a big advantage (for a good example look how the ScrollBar control template communicates with the control logic at http://msdn.microsoft.com/en-us/library/ms742173.aspx ).
In other cases commands can turn what would have been a 2 lines event handler into some impossible to follow monstrosity involving changing 4 separate places in the application (How should the ViewModel close the form? ).
The only reason is to have well know registry of commands. Means that events are likely to be private methods and I feel that they are tightly bonded to code of the window. At the same time Commands gives ability to keep implementation (event) and definition (Command) separately, you can even use another class (take a look on ApplicationCommands).
In addition, when I am doing my WPF work I use implementation of the ICommand(Command Pattern). All logic of the command goes to the Execute method. This helps me to keep separation of logic in more structured way witout overcomplication of the window code. With this option you can create commands on your model and therefore bind them witout noise. Take a look.
Create model.
public class Model
{
ICommand CloseMessagePopupCommand {get; set;}
}
Then assign Data Context
public MainWindow()
{
this.DataContext = new Model();
}
And use follwing XAML code.
<Button
Command="{Binding CloseMessagePopupCommand}"
Content="{StaticResource Misc.Ok}" />
I try to stay true to the command pattern that Mike refers to when developing WPF applications, using a combination of Andy's #2 and #3 approaches.
I can think of only one downside of commands in my view: only certain actions of certain UI elements invoke commands. One way to get around this is to have your event handler call the Execute method on a command. I think that commands provide a very good way to encapsulate execution logic. If you maintain a large piece of UI and implement it using a MVC/MVC/MVVM pattern, this becomes very apparent.
I encourage you to take a look at Dan Crevier's series on the DataModel-View-ViewModel pattern, in particular the section on Commands and Encapsulating Commands. Even if this pattern doesn't meet your needs, it gives a great overview of how you can encapsulate logic inside a separate class.
Other variations on ICommand seem to be a popular way to implement complex command structures.
Brian Noyes in his article on PRISM says
Routed commands in WPF are very powerful and useful, but they have some shortcomings when applied to a composite application. The first is that they are entirely coupled to the visual tree-the invoker has to be part of the visual tree, and the command binding has to be tied in through the visual tree. ... The second shortcoming is that they are tightly tied in with the focus tree of the UI and goes on to talk about the DelegateCommand and CompositeCommand which CAL (Prism) includes.

Resources