WPF – CanExecute refreshed

When you are developing a WPF application based on the MVVM pattern, the buttons are connected using RoutedCommands. These commands are linked with an Execute and a CanExecute event handler. The CanExecute event handler will define if the action is available or not.

Below, a simple application representing a buttom allowing to call the existing OpenFile dialog ApplicationCommands.

<Window x:Class="OnOff.Window1"
    Height="100" Width="100">
        <CommandBinding Command="ApplicationCommands.Open" CanExecute="CommandBinding_CanExecute"/>
        <Button Margin="5,5,5,5" Content="Open File" Command="ApplicationCommands.Open"/>

Now imagine that you want that you button can be called only every 2 seconds. Your CanExecute event handler will look like that:

private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    e.CanExecute = (DateTime.Now.Second % 2 == 0);
    e.Handled = true;

Then you start your application and the button’s state does not change. Why ? The CanExecute event is only raised when the context has changed, or when the window needs to be refreshed.

You can resolve this problem using CommandManager. InvalidateRequerySuggested(), charged to evaluate again all commands. In order to avoid manual calling to this method, you need to consider the usage of a DispatcherTimer. This dispatcher will be associated with the dispatcher of WPF, and thus you will not meet some cross-threading problems.

// Usings 
using System.Windows.Threading;

// Defines a new Dispatcher associated to the WPF Thread
DispatcherTimer dispatcher = new DispatcherTimer();

// Defines the interval of calling the dispatcher
dispatcher.Interval = TimeSpan.FromMilliseconds(500);
dispatcher.IsEnabled = true;

dispatcher.Tick += delegate

The result will be the following, changing the state of the button every 2 seconds.



2 thoughts on “WPF – CanExecute refreshed

    1. Hi Vikas,

      You need to add [ ] around each ‘sourcecode’ tag:

      sourcecode language=”csharp”
      Console.Write(“Hello Vikas”);

      Console.Write("Hello Vikas");


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s