WPF Commanding – When do Commands re-evaluate their CanExecute method?

I had been merrily using WPF’s built-in support for the Command Pattern for ages (see Commanding Overview, MSDN Docs, and article on implementing the command pattern in WPF, Jeff Druyt)… when suddenly it occured to me that I had no idea what triggered WPF to determine whether or not a command can be executed.

Let me explain by reduction to an absurd example:

Say I have a command that can only execute when

DateTime.Now.Second % 2 == 0.

I construct this command by home-brewing a static RoutedCommand instance:

public static class Commands

{

public static RoutedCommand MyCommand { get { return m_MyCommand; } }

private static RoutedCommand m_MyCommand = new RoutedCommand

(

“Execute My Command”,

typeof(Commands),

new InputGestureCollection()

{

new KeyGesture(Key.C, ModifierKeys.Alt)

}

);

}

And then I add a Command Binding for that command to my Window, and assign the command to a Button:

<Window x:Class=”TestCommands.Window1″…>
<Window.CommandBindings>
<CommandBinding
Command=”{x:Static local:Commands.MyCommand}”
Executed=”MyCommandExecuted”
CanExecute=”MyCommandCanExecute”
/>
</Window.CommandBindings>

<Button Width=”200″ Height=”200″
Command=”{x:Static local:Commands.MyCommand}”
Content=”{Binding Path=IsEnabled}”
/>

</Window>

By nature of WPF’s awesomeness and WPF Commanding in general, the above Button’s IsEnabled property should automatically be set to true or false based on whether or not the command can or can’t be executed.

Speaking of which, let’s set up my Command’s absurd logic in the CodeBehind by implementing its Execute and CanExecute event handlers:

private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)

{

DateTime now = DateTime.Now;

if (CanExecuteOutput != null)

{

CanExecuteOutput.Text = “MyCommand CanExecute determined at “ +

now.ToLongTimeString() + ” (and “ + now.Millisecond + “ms)”;

}

e.CanExecute = DateTime.Now.Second % 2 == 0;

}

private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e)

{

TextOutput.Text = “MyCommand executed at “ + DateTime.Now.ToLongTimeString();

}

So, my example is absurd but I bet you see my point by now: WPF is meant to automatically set the IsEnabled Property on that button to true or false, based on the results of the CanExecute method. But in this case, the results of CanExecute are a function only of time, and thus change repeatedly and independently of “obvious” application events. So… how does the Commanding system know when to query CanExecute and consequently enable/disable the button once a second?

In this case, without further intervention, it doesn’t. It seems that when events are raised on the Window (a mouse button click, etc.), CanExecute is re-evaluated. (I don’t know the details and wish I did.)  But, without further programmatic or user intervention, the button will not automatically change its IsEnabled state once a second.

This led me back to the MSDN docs, where I discovered the aptly-named InvalidateRequerySuggested event. To coerce – er, suggest – that WPF should query CanExecute, I set up the following DispatcherTimer:

m_DispatcherTimer = new DispatcherTimer()

{

Interval = TimeSpan.FromSeconds(0.25),

IsEnabled = true

};

m_DispatcherTimer.Tick += delegate

{

CommandManager.InvalidateRequerySuggested();

};

Now, the IsEnabled property of the Button blinks on and off as the Command’s ability to be executed changes with the passing seconds.

Only then did I discover there’s an MSDN Docs sample called “Disable Command Source Via Dispatcher Timer Sample” which is remarkably similar.

There you have it. Now go forth and command WPF’s Commanding. I’m sure you can all execute on that request <g>

P.S. Code for this sample is here.

P.P.S. What are folks using for pasting XAML and C# code into their blogs? This entry is looking a little rough…

Learn WPF by example (a recipe)

Ever wonder how the experts build clever things into their WPF applications? Here’s one way to find out which uses a few of my favourite tools for building WPF and Silverlight apps.

Required Ingredients:

1. Snoop, an excellent utility that lets you visualize and probe a running WPF application.

2. Lutz’s tried and true Reflector utility, which lets you view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL.

3. A WPF application that you’d like to learn from. For example, Expression Blend 2, which is used for making WPF applications and was also made with WPF itself. (More examples follow :) )

Steps:

0. Add the assemblies (.DLL and .EXE files) from the interesting WPF application into Lutz’s Reflector.

1. Run the WPF application that you’d like to learn from. As an example, run Expression Blend, and ponder how they make those nice search textboxes with the word “Search” greyed out behind your text. (I know, they’re actually pretty simple – this is just an example)

2. Run Snoop to peer in on the WPF process. In this case, Blend itself.

3. Hold down Ctrl-Shift while mousing over the element that you’d like to learn about. In this example, discover with Snoop that what you’re looking for here is a custom control of Type OverlayTextBox.

4. In Reflector, look up the Type you’d like to better understand. In this example, just search for OverlayTextBox, and discover it’s a TextBox with a few extra DependencyProperties and Methods.

5. Learn by expert example.

Here are some other apps you might want to spelunk using this technique. For these two, the source is also available, which can make for an even more thorough investigation.

Kevin Moore’s WPF Bag of Tricks – an expertly-constructed set of samples from Kevin Moore, a former member of the WPF team.

Avalon Healthcare Monitoring Demo – the medical dashboard demo I showed at the O# VS2008 at the Movies Event. Built in the WPF 3.0 era but still an excellent learning resource.

WPF Training

Speaking of learning WPF: you may be interested in the hands-on WPF training course offered through my consultancy, Carrington Technologies. Please see here for more information.

WPF Training Course

IIA and Enterprise Ireland Net Visionaries Awards

IIA Net Visionary AwardsI have long suspected that the Irish are mad, and now I have proof.

At some point during the National Productivity Centre crunch time, I received a mail from Irene Dehaene, informing me that I’d been nominated for the Best Blogger award at the IIA and Enterprise Ireland Net Visionary awards next month. 

I was overwhelmed, and remain extremely grateful to the person or people who nominated me.  It is tremendously gratifying to know that while I was living in Dublin, stumbling to keep with a finger on the tech scene pulse and keep developers informed and enthused about what was coming down the pipe, someone was listening and appreciating what I had to say.  It’s an honour to be recognized for that.

But I’m not the best blogger in Ireland.  I have incontrovertible proof of this fact: I’m currently in Canada.  In fact, I’m in Windsor, which some of you may know as the town across the border from Detroit where, according to Michael Moore, nobody locks their doors.

Since Twenty Major is incomprehensibly not on the shortlist, and Podge and Rodge aren’t yet blogging, I don’t have a candidate I can wholeheartedly throw my voting weight behind.  So I wish the very best to all the candidates and, again, am very grateful for the honour. 

And I hope that those who are still answering Ireland’s Call keep reading — I now have the new and hopefully interesting perspective of being a globetrotting Canadian, now an independent IT consultant, who had the good fortune of living and working in Ireland for 6 years. 

And, believe me, the “6 years living and working in Ireland” bit makes for some amazing story value back here in Canada.

Right.  I’m off to Guatemala for a bit.  I’ll post some pics of beautiful autumnal Canada first.

National Productivity Centre Launch

You’d be forgiven for being surprised to find out that I haven’t yet begun my travels, and haven’t even dipped my toe in the water for more scuba.

Instead, I’ve been working as an independent consultant for the past few weeks, helping to complete the development of the first application for Ireland’s National Productivity Centre, a joint venture between the Irish Management Institute and Microsoft Ireland, who are supported in their effort by a host of industry collaborators.

MSR Teleconferencing App at the NPC

The environment of the National Productivity Centre (NPC) is the coolest part: A boardroom with seven enormous wrap-around screens, a table full of tablet PCs, teleconferencing gear straight outta Microsoft Research, and all the supporting technology you could eat. As much as I like the applications that have already been developed for the NPC, my head is swimming with ideas for what could be built for that space.

National Productivity Centre - Case Study App

Part of the first NPC application (shown in the photo above) integrates Virtual Earth with a Windows Presentation Foundation front-end to provide a geographically-partitioned view of case studies where Microsoft technologies are being put to work to simplify how people work together and improve business insight.

And so my time in Ireland (to date) now ends as it began: with a demo for Irish Prime Minister Bertie Ahern (below).

Prime Minister Bertie Ahern launches the NPC

My good friend Damian Isla was a major part of the original Irish demo adventure, which culminated with Bertie, man of the people, herding virtual sheep on national television. Now, after thoroughly enjoying the celebration of Damian’s marriage to his incredible wife Julie, it’s time for some much-needed rest, after which I’ll enjoy the fruits of Damian’s most recent (technical) labour!