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 "))
                            .OnSuccess(Add)
                   .ToAction()
                   .SuccessVisualState(ItemVisualStates.Add)
               ).ToCommand();

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

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

Inheriting a DefaultStyle

This is mainly for me. I always forget how to do this and when ever I need it I can’t find it!

How do you specify a style for a control but still implement the default style for that control?

Add this line to your style definition (example for a button)

BasedOn="{StaticResource {x:Type Button}}"

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.

Simple Empty Template for ItemsControls

One of my favourite elements in WPF is the VisualBrush. It allows you to define content (i.e. XAML) and then use it where ever you can use a brush.

Using this brush we can easily define content for an ItemsControl when it has no items.
We set a datatrigger to watch the Items.Count and when it’s zero make the background whatever content you want. In this example I just whack in some text.
As such:

<ListBox Height="100" Width="100"   ItemsSource="{Binding ItemsToBind">
  <ListBox.Style>
    <Style TargetType="ListBox" >
      <Style.Triggers>
        <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" 
                     Value="0">
          <Setter Property="Background">
            <Setter.Value>
              <VisualBrush Stretch="None">
                <VisualBrush.Visual>
                   <TextBlock Text="No Items" />
                </VisualBrush.Visual>
              </VisualBrush>
            </Setter.Value>
          </Setter>
        </DataTrigger>
      </Style.Triggers>					
    </Style>
  </ListBox.Style>
</ListBox>

PopUp Dialog Behaviour

Based on the StaffLynx application’s modal control-based popups and inspired by this post by Brad, I set about creating a PopUp Dialog Blend Behaviour and sample which I have put into the Expression Gallery.

Sample

The behaviour allows for Dialogs to be easily added to a WPF application. If the dialog is Modal, it is modal to any part of the window (not just the whole window) i.e. a Tab. This allows for non-linear application navigation as the entire window is not locked down.

The behaviour is applied to any grid (other panels aren’t supported at the moment), if it is modal this will be the area that is disabled when the dialog appears. The showing and hiding of the dialog is controlled by the Visible dependency property on the behaviour, and the modal drum skins color and opacity can be set. There is currently no support for animation, but could easily be added (please send in the changes if you do 🙂 )

The dialog is any UiElement as in this sample is a usercontrol (line 5).

Behavior XAML from the Sample

<Grid Grid.Row="1">
      <e:Interaction.Behaviors>
        <ch:PopUpBehaviour x:Name="SampleDialog" Modal="true" Visible="{Binding ElementName=Go, Path=IsChecked, Mode=TwoWay}">
          <ch:PopUpBehaviour.PopUp>
            <Sample:Dialog />
          </ch:PopUpBehaviour.PopUp>
          <ch:PopUpBehaviour.ModalBehaviour>
            <ch:DisableBackGroundBehaviour Background="Pink" />
          </ch:PopUpBehaviour.ModalBehaviour>
        </ch:PopUpBehaviour>
      </e:Interaction.Behaviors>

The main reason I started looking into alternatives to Brad’s solution was a better separation of visuals and behaviour, primarily ease of styling of the actual dialog.  It also puts any behaviour requirements in the hands of the dialog designer. If you want dragability or resiziability you have to implement it, thankfully it’s as easy as adding other blend behaviours. The below code snippet is the contents of a sample dialog, it can be any UiElement .

Dialog XAML from the Sample

 <Border BorderThickness="1" Background="BlanchedAlmond"  Width="150" Height="150">
    <e:Interaction.Behaviors>
      <il:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </e:Interaction.Behaviors>
    <dropShadow:SystemDropShadowChrome>
      <DockPanel Background="White" Opacity="1" Margin="1">
        <UniformGrid DockPanel.Dock="Bottom">
          <Button Command="ApplicationCommands.Close" Width="50">Close</Button>
        </UniformGrid>
        <TextBlock DockPanel.Dock="Top" Text="Dialog" />
      </DockPanel>
    </dropShadow:SystemDropShadowChrome>
  </Border>

To Close the dialog you can either set the behaviour Visible property to false or execute the ApplicationCommands.Close command as per the sample. (Line 8 in the dialog)

A more MVVM oriented Dialog Service based on this behaviour will soon be released in Present.

Single Responsibility Misuse

The Inquisitive Coder recently made a post about MVVM being overrated. He states a preference for MVP (a great pattern, and a great implementation of it for WPF is Caliburn). Whilst patterns are there to be abused used as the needs of a project dictate. I think the arguments are subject to a common flaw in peoples thinking, especially around front-end patterns.

The primary attack on MVVM is that it violates the Single Responsibility Pattern (SRP). In short SRP states that a class should have one and only one reason to change. David suggests that ViewModels have 2 reasons to change (paraphrased)

  1. If, the Model changes
  2. If, the View requirements change ( i.e. needs more model data displayed/edited)

This is not what I take issue with, it’s true. But it’s true of all bridge classes and interfaces; DTO’s, Data Layers and UI’s. A bridge depends on both sides, but that is it’s responsibility. Sometimes the SRP is looked at from a much to granular view point and it leads to anaemic domains. People want to separate data from behaviour it seems to be human nature. I regularly hear SRP as the reason why this is good.

From Daniels post the 2 responsibilities a ViewModel has are:

  • communication/interaction with the Model
  • making data (from the Model) available so it can be displayed

Rephrased

  • Behaviour
  • Data

The SOLID principles (of which the S stands for SRP) are a great way to evaluate code and patterns, but they take a back seat to the tenets of OO Design

  • encapsulation
  • inheritance (I think this should be renamed Inheritance and Composition or removed as being implicit in polymorphism)
  •  polymorphism

Encapsulation states thou shall not whore out your data to other classes. Whilst UI is a grey area for encapsulation as we all need to display our data. MVVM takes a step closer to encapsulation by keeping the behaviour and data together.

In my opinion ViewModels contain their data and the behaviour that relies on it in one place with the single responsibility of Modelling a View.  If your ViewModels are two big or unwieldy then look at decomposing them into self contained Commands (with both data and behaviour) and/or smaller ViewModels with clearer responsibilities (an upcoming post).

Side Note
After 18 months of MVVM I too am starting to wonder if the extra work required to maintain two-way synchronization (View-Model) is worth it for most scenarios. But that’s another topic and to do with choosing the right tool for the job. I still believe MVVM is the most elegant pattern for solving the problem it solves.

MVVM Validation and Type Checking

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

ScreenShot

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 
 <StackPanel>
        <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}}" />
        </Controls:Form>
        <Button Content="Save" Command="{Binding SaveCommand}" Width="50"/>
    </StackPanel>

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.

Binding Syntax – Attached Properties

CommandParameter="{Binding
Path=(Grid:GridPopupMenu.GridMenuInfo).Menu.(Dx:GridViewBehaviours.MenuRowData),
RelativeSource={RelativeSource Self}}"

Working with a Third-Party library that isn’t necessarily designed with MVVM in mind 😉 I often need to play around with Attached Properties to achieve the desired result. One of the great things with WPF bindings is that you can combine any of the supported notations into a large chain (as above).

The properties wrapped in () are attached properties, the first is being applied to the control in question (due to RelativeSource=Self), the second is being applied to the Menu control.