Requery Not Suggested

During my first WPF project I noticed (like most people starting in WPF do) that DelegateCommand.CanExecute is called once and never refreshed. To force a refresh one must call RaiseCanExecuteChanged when the state of CanExecute has changed. That had a few smells about it and was cubersome, so when I stumbled across CommandManager.RequerySuggested I thought all my problems were solved.

From MSDN ”Occurs when the CommandManager detects conditions that might change the ability of a command to execute.”

All I did was create my own DelegateCommand and proxy the CanExecutedChanged event to the CommandManager.RequerySuggested event and every time WPF noticed something change it would force a refresh of my CanExecute methods. I even had the audacticity to call it BetterDelegateCommand!!

This didn’t cause too many problems on the project, as a general rule people know to keep the CanExecute logic quick and we had linear navigation in the application so there wouldn’t have been more than 10 commands bound at anyone point.

Things quickly change when you move to apps that have multiple windows/dialogs/plugins loaded and hundreds of commands can be bound. Spice that up with a developer adding CanExecute methods that do a little more than test the value of a variable and you get a significant slowdown which is very hard to debug.

Because there are times when using the RequerySuggested method is preferable Present.Commands provides the RequeryCommandDecorator and fluent method.

MyCommand = Command.Async(new SomeAction())

For everything else there is the CanExecuteChangedDecorator and fluent command. It allows you to specify an Observable which it subscribes to, when a notification comes through the CanExecuteChanged event is fired. Using an Observable adds a powerful filtering and joing tool to define when the command ‘s state has changed.

  MyCommand = Command.Async(new SomeAction())
                                .CanExecuteChangedWhen(this.WhenPropertyChanges(x => x.SomeProperty));

MVVM Animation of ListBox – Present.Commands

Using the Present.Command decorator to change visual states after a command execution we can easily animate the addition and deletion of items in a WPF ListBox in an MVVM friendly way.
(The code is in svn for the async command samples)

Firstly, our ViewModel’s: we have an ItemViewModel representing an item in the ListBox; and an ItemCollectionViewModel representing our ListBox. Our ItemCollectionViewModel contains the two commands we are primarily focused on, Add and Delete.


  AddCommand = Command.Async
                       .Do(x => new ItemViewModel("New Item "))

Pretty self-explanatory, we create a new item, Add it to the collection and change the state of the new item viewmodel to “Add”


DeleteCommand = Command.Async
                    AsyncAction.FromDelegates<ItemViewModel, ItemViewModel>()
                        .Do(e =>
                                    e.Parameter.IsDeleting = true;
                                    return e.Parameter;
  .SuccessVisualState(ItemVisualStates.Delete, item => Remove(item))

The delete command is a little more involved. We set the Parameter (the item to delete) to “deleting” and sleep to simulate server call. Once we have deleted it on the server we play the delete animation (by changing the visual state to delete) and then once everything is finished we remove the item from the collection.

ListBox Item DataTemplate

          <!--Register the View, so it is acessible from Services, bind the current visual state so the ViewModel can control it-->
          <UniformGrid Name="grid" Style="{StaticResource DemoGrid}"  VerticalAlignment="Center" Commands:PresentVisualStateManager.GoToState="{Binding State}"
              <VisualStateGroup x:Name="ActionStates">
                <VisualState x:Name="Add"  Storyboard="{StaticResource AddAnimation}"/>
                <VisualState x:Name="Delete"  Storyboard="{StaticResource DeleteAnimation}"/>

            <Button Command="{Binding DataContext.DeleteCommand, ElementName=List}" CommandParameter="{Binding}" Height="20" Width="20">
                <Style TargetType="Button" BasedOn="{StaticResource ImageButton}">
                    <DataTrigger Binding="{Binding IsDeleting}" Value="True">
                      <Setter Property="Content">
                          <Viewbox Width="{TemplateBinding Button.Width}" Height="{TemplateBinding Button.Height}">
                            <Progress:CircularProgressBar />
                    <DataTrigger Binding="{Binding IsDeleting}" Value="False">
                      <Setter Property="Content">
                          <Image Source="{StaticResource imgMediumCross}"
                                 Width="{TemplateBinding Button.Width}"
                                 Height="{TemplateBinding Button.Height}" />

              <Label Content="{Binding Name}" />



Here we define the VisualStates Add and Delete and their corresponding animations (static resources)
We change the Button image to a circular progress bar whilst we are deleting.
We register the View with the ViewRegistry and bind to the delete command.
With a little more designer input we have a beautiful animating listbox 😉

Visual State Change In a Command

Using the Present VisualStateManager and the ViewRegistry we can now use a Present.Commands  decorator  to change the visual state of a ViewModel after succesful execution of the decorated command.

 The decorator has a number of overloads, the ViewModel to change state of can be passed in or returned by the do action; an action can be executed after the state transition as well.

  AddCommand = Command.Async
                   AsyncAction.FromDelegates<object, ItemViewModel>()
                            .Do(x => new ItemViewModel("New Item "))

The view has to then register itself with the registry and define a VisualState using the constant passed into the fluent method.

Auto Mocking EventAggregator

A general rule about Unit Testing that I try to follow is that a change in the class under test should not break the test, unless the functionality under test is broken. It just makes things more maintainable.

For a long time, when I tested ViewModels I had a method called

StubEvent<TEvent, TPayload>()

This allowed me to stub all the required events for a test and control flow. However, when someone added a new event subscription or publication into the ViewModel,  the tests would fail as no one stubbed the new event; breaking the above rule.

The second problem when people started subscribing to Events on the UI Thread using

event.Subscribe(DoSomething, ThreadOption.UIThread);

The UIThread subscription uses Application.Current.Dispatcher which obviously isn’t there in most Unit Tests and so your subscriptions fail.

Enter AutoMockingEventAggregator; this bad boy returns a stubbed version of any event requested and adds a Dispatcher that can be used in testing. Just replace your mocked or concrete IEventAggregator with an instance of AutoMockingEventAggregator and all your testing woes are gone 😉
I even throw in a free AssertSubscriptionWasOnUiThread method.

On a separate note, if you aren’t committed/forced to use Prism’s EventAggregator, have a look at the Observable alternatives such as this one.

VisualStateManager – Execute after Transition Finished

The VisualStateManager (VSM) is a class that allows you to define visual states (think Enabled, Disabled, MouseOver, Deleting, Saving) and programmatically move to those states.  (Part of WPF 4.0, for users of 3.5 you can get it as part of the WPFToolkit)

A great demo and walkthrough of using the VSM is here.

One of the draw backs of using the VSM has been the inability to be notified when the state transition has completed. For instance, say you wanted to animate the removal of an item from a ListBox i.e. some fancy fade and shrinking. You would create a Delete VisualState and when the user deletes you would transition to the Delete state and then remove the item from the list….. or would you?

Animations are kicked off by the VSM and control returned to the calling thread (it’s non-blocking). So in actual fact you will remove the item from the list before the animation really gets going and your databinding will remove the visual item from the ListBox without out all your fancy fade and shrink 😦

Enter PresentVisualStateManager, part of a wider demo (coming soon) of Present Fluent Commands. It allows you to execute an action after the animation has finished, by hooking into the StoryBoard Completed event
Classes are here:

A more MVVM friendly service is in the making but until then a control is passed into ChangeState (ala GotoState and GotoElementState), with the desired state name and an action to perform after the transition completes. ChangeState first calls GoToState (for Visuals defined in ControlTemplates) and if that fails to find the state it calls GoToElementState (for Visuals defined inline)

PresentVisualStateManager.ChangeState(grid, "Delete", () =>  this.itemsCollection.Remove(item.DataContext as ItemViewModel));

WPF Fluent Commands

When writing a Command in WPF there can be a number of behaviours a command may need, to fulfil it’s purpose, which are actually orthogonal to the actual responsibility of the command (let’s say saving). For example the command may need to be scheduled (in the case of Auto-Save), it may need to “busy” the View, be executed asynchronously and ensure the current user has the authorisation to save the current item. Not only that, but the delete command and the load commands may also have to do the same things!

Present‘s Fluent Commands was born to enable the reuse of these common command decorations and allow the composition of commands using a fluent api.  (recently moved to Google Code)

The inner command (Save) is wrapped in a number of decorators each which add a single extra function to the inner command. Present currently has three Command Decorators

  • Schedule Decorator – Repeatedly executes a command every given time period.
  • Requery Decorator – Commands such as Prisms DelegateCommand rely on consumers to raise the CanExecutedChanged event to force the UI to reevaluate the CanExecute value of the command. This is not always feasible. This Decorator wires the CanExecutedChanged event to the CommandManager.RequerySuggested event so the CanExecute method is regularly re-evaluated.
  • Selectable Decorator – A decorator that exposes Properties the UI can use for binding “Selectability”.

More can easily be added, for instance internally we have a security decorator and a maximum concurrent executions decorator.

Scheduled Command

The second addition is Asynchronous behaviour. The AsyncCommand and CompositeAsyncCommand take AsyncActions which describes the life cycle of the operation and are executed using a BackgroundWorker.  The composite command allows for simultaneous asynchronous execution of multiple actions as well as an action to be executed when all actions have completed. Actions can also be decorated with extra behaviour such as the BusyAsyncActionDecorator which busys the View or the ObservableAsyncActionDecorator which turns the action into an Observable.

Async Command

Fluent Commands has now been released as part of Present (recently moved to Google Code).
A sample app can be dowloaded here.

MVVM Validation and Type Checking

This post is based on Present.Validation a part of the Present project at codeplex.


Present.Validation is an implementation of IDataErrorInfo for MVVM which uses a pluggable contributor pattern to provide validation. It currently has a single contributor for use with System.ComponentModel.DataAnnotations. Validation can then be acheived by decorating the ViewModel properties with attributes

 [Range(0, 120, ErrorMessage = "Age must be between 0 and 120")]
public int Age 
        <v:BrokenBindingNotifier PropertiesWithBrokenBindings="{Binding Validator.BrokenBindings}" />
        <Controls:Form Padding="20">
            <TextBox Controls:FormItem.LabelContent="_Firstname" Text="{v:ValidatedBinding FirstName}" />
            <TextBox Controls:FormItem.LabelContent="_Lastname" Text="{v:ValidatedBinding LastName}" />
            <TextBox Controls:FormItem.LabelContent="_Age" Text="{v:ValidatedBinding Age, TargetNullValue={x:Static System:String.Empty}}" />
        <Button Content="Save" Command="{Binding SaveCommand}" Width="50"/>

There are plenty examples of implementing IDataErrorInfo on the web, but they tend to ignore broken bindings. Broken Bindings occur for a number of reasons such as the binding source can’t be found or the Path is invalid. They also occur when the input value can’t be coerced back to the data type of the source.

For example if someone tries to enter Twelve into a text box bound to the int Age property the binding will break; leaving the value of Age unset and the ViewModel unaware of the error.

Present.Validation tackles this via a binding notifier which binds broken bindings to the a validator. (Line 2 of the Xaml). It also uses a custom binding ValidatedBinding which just sets all the needed error checking properties to true.

Gotcha: Nullable Types

Watch out when using nullable types that you set the TargetNullValue as for the Age binding. An empty textbox is set to String.Empty which isn’t compatible with int?. So we need to tell WPF that String.Empty is equal to Null.