<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>robburke.NET &#187; Commanding</title>
	<atom:link href="http://robburke.net/tag/commanding/feed/" rel="self" type="application/rss+xml" />
	<link>http://robburke.net</link>
	<description>Robert Burke&#039;s home on the web.</description>
	<lastBuildDate>Wed, 18 Apr 2012 19:15:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>WPF Commanding &#8211; When do Commands re-evaluate their CanExecute method?</title>
		<link>http://robburke.net/2008/04/wpf-command-pattern-when-does-it-query-canexecute/</link>
		<comments>http://robburke.net/2008/04/wpf-command-pattern-when-does-it-query-canexecute/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 13:30:23 +0000</pubDate>
		<dc:creator>Rob Burke</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Command Pattern]]></category>
		<category><![CDATA[Commanding]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://robburke.net/?p=105</guid>
		<description><![CDATA[I had been merrily using WPF&#8217;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)&#8230; 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 [...]]]></description>
			<content:encoded><![CDATA[<p>I had been merrily using WPF&#8217;s built-in support for the Command Pattern for ages (see <a href="http://msdn2.microsoft.com/en-us/library/ms752308.aspx">Commanding Overview</a>, MSDN Docs, and <a href="http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wpf_commandpattern.mspx">article on implementing the command pattern in WPF</a>, Jeff Druyt)&#8230; when suddenly it occured to me that I had no idea <em>what </em>triggered WPF to determine whether or not a command can be executed.</p>
<p>Let me explain by reduction to an absurd example:</p>
<p>Say I have a command that can only execute when</p>
<p style="padding-left: 30px;"><strong><span style="color: #2b91af;">DateTime</span>.Now.Second % 2 == 0</strong><strong>.</strong></p>
<p>I construct this command by home-brewing a static RoutedCommand instance:</p>
<div style="background: white none repeat scroll 0%; font-family: Courier New; font-size: 10pt; color: black; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">Commands</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px; padding-left: 30px;"><span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">RoutedCommand</span> MyCommand { <span style="color: blue;">get</span> { <span style="color: blue;">return</span> m_MyCommand; } }</p>
<p style="margin: 0px; padding-left: 30px;">
<p style="margin: 0px; padding-left: 30px;"><span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">RoutedCommand</span> m_MyCommand = <span style="color: blue;">new</span> <span style="color: #2b91af;">RoutedCommand</span></p>
<p style="margin: 0px; padding-left: 30px;">(</p>
<p style="margin: 0px; padding-left: 30px;"><span style="color: #a31515;"> &#8220;Execute My Command&#8221;</span>,</p>
<p style="margin: 0px; padding-left: 30px;"><span style="color: blue;"> typeof</span>(<span style="color: #2b91af;">Commands</span>),</p>
<p style="margin: 0px; padding-left: 30px;"><span style="color: blue;"> new</span> <span style="color: #2b91af;">InputGestureCollection</span>()</p>
<p style="margin: 0px; padding-left: 30px;">{</p>
<p style="margin: 0px; padding-left: 30px;"><span style="color: blue;"> new</span> <span style="color: #2b91af;">KeyGesture</span>(<span style="color: #2b91af;">Key</span>.C, <span style="color: #2b91af;">ModifierKeys</span>.Alt)</p>
<p style="margin: 0px; padding-left: 30px;">}</p>
<p style="margin: 0px; padding-left: 30px;">);</p>
<p style="margin: 0px;">}</p>
</div>
<p>And then I add a Command Binding for that command to my Window, and assign the command to a Button:</p>
<p>&lt;Window x:Class=&#8221;TestCommands.Window1&#8243;&#8230;&gt;<br />
<strong>&lt;Window.CommandBindings&gt;<br />
&lt;CommandBinding<br />
Command=&#8221;{x:Static local:Commands.MyCommand}&#8221;<br />
Executed=&#8221;MyCommandExecuted&#8221;<br />
CanExecute=&#8221;MyCommandCanExecute&#8221;<br />
/&gt;<br />
&lt;/Window.CommandBindings&gt;<br />
</strong>&#8230;<br />
&lt;Button Width=&#8221;200&#8243; Height=&#8221;200&#8243;<br />
<strong> Command=&#8221;{x:Static local:Commands.MyCommand}&#8221;<br />
</strong> Content=&#8221;{Binding Path=IsEnabled}&#8221;<br />
/&gt;<br />
&#8230;<br />
&lt;/Window&gt;</p>
<p>By nature of WPF&#8217;s awesomeness and WPF Commanding in general, the above Button&#8217;s IsEnabled property should automatically be set to true or false based on whether or not the command can or can&#8217;t be executed.</p>
<p>Speaking of which, let&#8217;s set up my Command&#8217;s absurd logic in the CodeBehind by implementing its Execute and CanExecute event handlers:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20         \cf3 private\cf0  \cf3 void\cf0  MyCommandCanExecute(\cf3 object\cf0  sender, \cf4 CanExecuteRoutedEventArgs\cf0  e)\par ??        \{\par ??            \cf4 DateTime\cf0  now = \cf4 DateTime\cf0 .Now;\par ??            \cf3 if\cf0  (CanExecuteOutput != \cf3 null\cf0 )\par ??            \{\par ??                CanExecuteOutput.Text = \cf5 "MyCommand CanExecute determined at "\cf0  + now.ToLongTimeString() + \cf5 " (and "\cf0  + now.Millisecond + \cf5 "ms)"\cf0 ;\par ??            \}\par ??            e.CanExecute = \cf4 DateTime\cf0 .Now.Second % 2 == 0;\par ??        \}\par ??\par ??        \cf3 private\cf0  \cf3 void\cf0  MyCommandExecuted(\cf3 object\cf0  sender, \cf4 ExecutedRoutedEventArgs\cf0  e)\par ??        \{\par ??            TextOutput.Text = \cf5 "MyCommand executed at "\cf0  + \cf4 DateTime\cf0 .Now.ToLongTimeString();\par ??        \}\par ??} --></p>
<div style="background: white none repeat scroll 0%; font-family: Courier New; font-size: 10pt; color: black; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;"><span style="color: blue;">private</span> <span style="color: blue;">void</span> MyCommandCanExecute(<span style="color: blue;">object</span> sender, <span style="color: #2b91af;">CanExecuteRoutedEventArgs</span> e)</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;"><span style="color: #2b91af;"> DateTime</span> now = <span style="color: #2b91af;">DateTime</span>.Now;</p>
<p style="margin: 0px;"><span style="color: blue;"> if</span> (CanExecuteOutput != <span style="color: blue;">null</span>)</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">CanExecuteOutput.Text = <span style="color: #a31515;">&#8220;MyCommand CanExecute determined at &#8220;</span> +</p>
<p style="margin: 0px;">now.ToLongTimeString() + <span style="color: #a31515;">&#8221; (and &#8220;</span> + now.Millisecond + <span style="color: #a31515;">&#8220;ms)&#8221;</span>;</p>
<p style="margin: 0px;">}</p>
<p style="margin: 0px;">e.CanExecute = <span style="color: #2b91af;">DateTime</span>.Now.Second % 2 == 0;</p>
<p style="margin: 0px;">}</p>
<p style="margin: 0px;">
<p style="margin: 0px;">
<p style="margin: 0px;"><span style="color: blue;">private</span> <span style="color: blue;">void</span> MyCommandExecuted(<span style="color: blue;">object</span> sender, <span style="color: #2b91af;">ExecutedRoutedEventArgs</span> e)</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">TextOutput.Text = <span style="color: #a31515;">&#8220;MyCommand executed at &#8220;</span> + <span style="color: #2b91af;">DateTime</span>.Now.ToLongTimeString();</p>
<p style="margin: 0px;">}</p>
<p style="margin: 0px;">
</div>
<p>So, my example is absurd but I bet you see my point by now: WPF is meant to automatically set the <strong>IsEnabled</strong> 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 &#8220;obvious&#8221; application events.  So&#8230; <strong><em>how does the Commanding system know when to query CanExecute and consequently enable/disable the button once a second?</em></strong></p>
<p>In this case, without further intervention, it <em>doesn&#8217;t</em>.  It seems that when events are raised on the Window (a mouse button click, etc.), CanExecute is re-evaluated. (I don&#8217;t know the details and wish I did.)  But, without further programmatic or user intervention, the button will <strong>not </strong>automatically change its IsEnabled state once a second.</p>
<p>This led me back to the MSDN docs, where I discovered the aptly-named InvalidateRequerySuggested event.  To coerce &#8211; er, suggest &#8211; that WPF should query CanExecute, I set up the following DispatcherTimer:</p>
<p><!-- {\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20             m_DispatcherTimer = \cf3 new\cf0  \cf4 DispatcherTimer\cf0 ()\par ??            \{\par ??                Interval = \cf4 TimeSpan\cf0 .FromSeconds(0.25),\par ??                IsEnabled = \cf3 true\par ??\cf0             \};\par ??            m_DispatcherTimer.Tick += \cf3 delegate\par ??\cf0             \{\par ??                \cf4 CommandManager\cf0 .InvalidateRequerySuggested();\par ??            \};\par ??} --></p>
<div style="background: white none repeat scroll 0%; font-family: Courier New; font-size: 10pt; color: black; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">
<p style="margin: 0px;">m_DispatcherTimer = <span style="color: blue;">new</span> <span style="color: #2b91af;">DispatcherTimer</span>()</p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;">Interval = <span style="color: #2b91af;">TimeSpan</span>.FromSeconds(0.25),</p>
<p style="margin: 0px;">IsEnabled = <span style="color: blue;">true</span></p>
<p style="margin: 0px;">};</p>
<p style="margin: 0px;">m_DispatcherTimer.Tick += <span style="color: blue;">delegate</span></p>
<p style="margin: 0px;">{</p>
<p style="margin: 0px;"><span style="color: #2b91af;"> CommandManager</span>.InvalidateRequerySuggested();</p>
<p style="margin: 0px;">};</p>
</div>
<p>Now, the IsEnabled property of the Button blinks on and off as the Command&#8217;s ability to be executed changes with the passing seconds.</p>
<p>Only then did I discover there&#8217;s an <a href="http://msdn2.microsoft.com/en-us/library/ms771552.aspx">MSDN Docs sample called &#8220;Disable Command Source Via Dispatcher Timer Sample&#8221;</a> which is remarkably similar.</p>
<p>There you have it. Now go forth and command WPF&#8217;s Commanding.  I&#8217;m sure you can all execute on that request &lt;g&gt;</p>
<p>P.S. Code for this sample is <a href="http://robburke.net/links/TestWPFCommands.zip">here</a>.</p>
<p>P.P.S. What are folks using for pasting XAML and C# code into their blogs? This entry is looking a little rough&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://robburke.net/2008/04/wpf-command-pattern-when-does-it-query-canexecute/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
	</channel>
</rss>

