Archive

Posts Tagged ‘Sticky ViewModel’

The Sticky ViewModel Pattern

December 16, 2009 1 comment

A Sticky ViewModel is a special type of Sticky Component which adds functionality to the ViewModel instead of to the View. By binding to the DataContext of its base element, the Sticky ViewModel is able to provide services which the ViewModel itself doesn’t include. In this respect, it is similar to the Mini-ViewModel pattern, which you might prefer if you want to provide an encapsulated reusable View for the added functionality as well.

An Example

The model or ViewModel might have a property which contains a persons name. In the View, you might want to be able to edit first name and last name separately. I have already discussed this example in the context of the Stateless Sticky ViewModel pattern, so here I want to add some extra: the new implementation should format the name either John Smith or Smith, John, depending on a boolean property LastNameFirst which one can use to configure the behaviour.

The example is contained in the StickyComponentExample project which you will find in the WPFGluePublished solution on the Downloads page.

Using a Sticky ViewModel

Like any other Sticky Component, you would initialize a Sticky ViewModel in the resources of an element that wants to use them:

<Grid.Resources>
  <ex:NameStickyViewModel x:Key="viewModel"
      LastNameFirst="True" FullName="{f:StickyBinding Name}"/>
</Grid.Resources>

Using the LastNameFirst property, we specify that we want the full name displayed in the Smith, John format.

But what is the meaning of the {f:StickyBinding } markup extension? It is understood that the Sticky ViewModel somehow accesses the DataContext of its base element in order to enhance it. In fact, there is a DataContext property in the StickyViewModel base class which is synchronized with the base’s DataContext automatically.

However, if the Sticky ViewModel would get the information it needs directly from the DataContext, it would have to know its type, thus being closely coupled to the ViewModel, which we want to avoid, since we want to be able to re-use the Sticky ViewModel wherever we need its functionality. So, the idea is to get the necessary information from the DataContext through data binding. Unfortunately, since the Sticky ViewModel is not part of the logical WPF tree, normal bindings cannot access the base element’s DataContext implicitly, like child controls. So, we use a special binding class, the StickyBinding, which allows us to bind to the DataContext of the StickyViewModel, instead. By writing FullName=”{f:StickyBinding Name}” we instruct the StickyViewModel to look for the value it should edit in the Name property of the model the element is bound to.

As usual, the Sticky ViewModel is attached to its base through an attached property:

<Grid x:Name="base"
  ex:NameStickyViewModel.ViewModel="{DynamicResource viewModel}"
      HorizontalAlignment="Stretch">

In this case, we have to refer to it with a DynamicResource extension, since it is contained in the resources of the element it is used on and thus is referred to before it is declared. We could also put it into the page’s resources and use a StaticResource extension. (StaticResource extensions are less complicated, so they are a little bit safer and faster, but they can only be specified where the definition comes before the reference in the XAML). However, in the example, the NameStickyViewModel is used in a DataTemplate for a ListView. So, every row of the ListView needs its own instance of the Sticky ViewModel, otherwise the names from different rows will start mixing. We can make sure of this either by putting the declaration of the StickyViewModel into the DataTemplate itself, as I have done here, or by setting x:Shared=”False” where we declare it, which tells WPF to create a new instance of a resource every time it is accessed.

The rest of the DataTemplate defines three TextBoxes for each row:

<TextBox Text="{Binding Name, TargetNullValue='[New Customer]'}"
         Margin="30,0,0,0"/>
<TextBox Grid.Column="1" Text="{Binding ElementName=base,
  Path=(ex:NameStickyViewModel.ViewModel).LastName}"/>
<TextBox Grid.Column="2" Text="{Binding ElementName=base,
  Path=(ex:NameStickyViewModel.ViewModel).FirstName}"/>

The first TextBox is bound directly to the DataContext of the DataTemplate. It refers to the property in the model that contains the full name of a person. The other two TextBoxes are bound to the StickyViewModel that lives on the element named “base”; this element is the Grid from above.

Implementing the Sticky ViewModel Pattern

In order to support binding on their properties, Sticky ViewModels are derived from DependencyObject and expose their working properties as DependencyProperties. Configuration properties don’t need to be data bound, so they are defined as normal properties.

Like in the Stateless Sticky ViewModel, after implementing the logic which does what the model should do, the main point is distributing the change notifications from the different properties so that the logic is called at the right time. This happens in the OnPropertyChanged method of the Sticky ViewModel, which is originally defined in DependencyObject:

Protected Overrides Sub OnPropertyChanged(ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
    MyBase.OnPropertyChanged(e)
    Static changeInitiator As DependencyProperty = Nothing

    If changeInitiator Is Nothing Then
        changeInitiator = e.Property

        Select Case e.Property.Name
            Case "FullName"
                FirstName = DetermineFirstName(FullName)
                LastName = DetermineLastName(FullName)
            Case "FirstName", "LastName"
                FullName = DetermineFullName(FirstName, LastName)
        End Select

        changeInitiator = Nothing
    End If
End Sub

 

Again like in the Stateless Sticky ViewModel, we remember between invocations which property started the change and cancel subsequent invocations of the method. However, this time the code is a little bit shorter and cleaner and not distributed between different methods (I just notice that one could implement it the same way with a Stateless Sticky ViewModel, but alas… never get it perfect the first time.)

Under the Hood

The Sticky Component Framework supports the Sticky ViewModel pattern with two components: the StickyViewModel base class, which can be used to derive one’s own Sticky ViewModels, and the StickyBinding, which one needs to be able to bind to the properties of the Sticky ViewModel’s DataContext.

The StickyViewModel class mainly manages attaching and detaching the ViewModel on its base element:

Public Sub OnAttach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnAttach
    Me.DataContext = StickyComponentManager.GetDataContext(sender)
    StickyComponentManager.AttachDataContextChanged(sender, AddressOf _DataContextChanged)
    Attach(sender, e)
End Sub

Public Sub OnDetach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnDetach
    Me.DataContext = Nothing
    StickyComponentManager.DetachDataContextChanged(sender, AddressOf _DataContextChanged)
    Detach(sender, e)
End Sub

It adds a handler to the base’s DataContextChanged event, so that the DataContext stays synchronised with the base’s DataContext. DataContext is a DependencyProperty, so it provides its own change notifications. Furthermore, the class defines a generic ViewModel attached property which can be used in derived classes in order to attach the model to the element.

The StickyBindingExtension basically is a BindingExtension with a reduced set of properties (everything related to input and validation is not needed on the StickyBinding), and in principle delegates all it does to this binding:

Public Overrides Function ProvideValue(ByVal serviceProvider As System.IServiceProvider) As Object
    Dim target As System.Windows.Markup.IProvideValueTarget = serviceProvider.GetService(GetType(System.Windows.Markup.IProvideValueTarget))
    If target IsNot Nothing Then
        If TypeOf target.TargetProperty Is DependencyProperty Then
            If TypeOf target.TargetObject Is StickyViewModel Then
                Dim dataPath As String = "DataContext"
                If Not String.IsNullOrEmpty(Path) Then
                    If Path.StartsWith("/") Or Path.StartsWith("[") Then
                        dataPath &= Path
                    Else
                        dataPath &= "." & Path
                    End If
                End If
                Dim b As New Binding(dataPath)
                b.Source = target.TargetObject
                b.Mode = Mode
                b.Converter = Converter
                b.ConverterCulture = ConverterCulture
                b.ConverterParameter = ConverterParameter
                Return b.ProvideValue(serviceProvider)
            End If
        End If
    End If
    Return Me
End Function

 

The trick here is to prefix the binding’s path with the DataContext property and always use the target object as source. Thus, following the principles of WPFGlue, I avoid to implement my own version of change notification listeners and instead use what is already there. Since the DataContext is always synchronized with the the base’s DataContext and provides change notification, the StickyBinding will always be able to find the correct property without any explicit dependencies.

Notice that the last line in the block that creates the binding returns Binding.ProvideValue. This is necessary in order to mimic Binding’s behaviour in all contexts.

Comparing Stateless and Stateful Sticky ViewModel

As mentioned before, the main advantage of the Stateful Sticky ViewModel is that it bundles configuration properties in one place and forms a better defined unit than the Stateless version. Its main focus is on the base’s DataContext. Sticky Bindings don’t support binding to properties of elements in the logical tree, as it would be possible with the ElementName or RelativeSource properties of a normal binding. However, if one needs that, one can combine the two patterns and define attached properties on the Sticky ViewModel for no other purpose than to be able to bind them to logical tree elements, and access them through a reference to the base that is acquired during Attach and of course released during Detach.

Coming Soon…

The Sticky Component Framework is still once removed from a real application… the next step will be a Commanding Framework based on Sticky Components which allows to define RoutedCommands, their keyboard shortcuts and display texts in one place, delegating their invocations to methods or ICommand implementations in the ViewModel or model.

WPFGlue Patterns

November 5, 2009 4 comments

Let’s recapitulate the design requirements for WPFGlue components:

  • You shall not duplicate functionality that is already in the WPF framework.
  • You shall not mess with WPF’s correct function, like keeping objects from being freed and the like evil practices.
  • You shall not require code behind.
  • You shall not demand sub-classing controls.
  • You shall not demand interface implementations from your business objects (unless the interfaces are part of WPF itself), nor common base classes, nor any other construct that commits the developer to a strong coupling between your glue and his code.

The following design patterns have proved suitable for development under these constraints:

Sticky Properties (a.k.a. Attached Properties)

Attached properties can be used to extend the state of any element in WPF. They can be used in XAML, and neither the framework-supplied controls nor the business object model need to know them. So, they are suitable for WPFGlue.

Built-in examples for attached properties are the Canvas.Left and Canvas.Top properties, which the WPF Canvas uses to store the positions of its child elements.

Sticky Behaviours (a.k.a. Attached Behaviours)

Attached behaviours are a special kind of attached properties that register event handlers on the elements they are attached to. The event handlers provide additional functionality to the elements which is triggered through the elements standard events, while the implementation of the event handlers is contained in the class that defines the attached property.

A built-in example for a sticky behaviour is the SpellCheck.IsEnabled property, which adds the functionality of spell checking to controls based on TextBoxBase.

Josh Smith writes about attached behaviours in this article; Attached behaviours are introduced and defined by Nikhil Kothari here.

Sticky CommandBindings

Work like sticky behaviours, with the difference that they don’t handle events, but standard routed commands. Attaching a sticky CommandBinding to a WPF FrameworkElement means that this element will be able to handle the command, without having to change the original implementation of the element. A sticky CommandBinding should add / remove the CommandBindings when the value of an attached property changes.

Pete O’Hanlon gives an almost perfect example of this pattern here. Almost perfect because he uses a class CommandBinding instead of the CommandBindings collection, but this might be justified on his case since he expects the command to be used by many elements per page.

Sticky ViewModels (a.k.a. Mini-ViewModels)

Sticky ViewModels are ViewModels that don’t wrap a business object, but attach themselves to it and expose a specialized, reusable bit of functionality through their own properties and commands. Typically, a sticky ViewModel wouldn’t be the DataContext of a FrameworkElement, but it would be attached to the element as a sticky property and use the FrameworkElement’s DataContext to find the model it is supposed to work on. Controls inside the scope of the FrameworkElement would then bind to properties of the sticky ViewModel in order to benefit from it.

Quite often jobs like this are done through converters (Converters are classes that implement the IValueConverter interface). However, I view this as converter abuse. A converter is not intended for anything but type conversions, translating data between different data types and string presentations. If the intention of the solution is rather to achieve some more complex interaction between the View and the Model, I’d recommend a sticky ViewModel instead. Usually these cases are discovered by feeling the need to pass more information into the conversion routines than is readily available…

While Mini-ViewModel seems to imply that the functionality of such a class would normally be quite limited, I could imagine whole page ViewModels using this technique.

Colin Eberhardt describes the Mini-ViewModel pattern here and gives a nice example.

ViewModelKits

A ViewModelKit would be a class or set of related classes that can be instantiated and configured as XAML resources, and then be used as ViewModels through referencing the resource.

A built-in example for a ViewModelKit would be the CollectionViewSource class, which can be used to configure views of business object collections.

Sticky Markup (a.k.a. Custom Markup Extensions)

Custom markup extensions are classes derived from System.Windows.Markup.MarkupExtension, which can be used in XAML attributes using the markup extension syntax, like {Binding value}. Writing custom markup extensions is not documented very well in the WPF documentation, and I use them sparingly. They need to be initialized in place, i.e. where they are used in XAML. This limits their “stickiness” to situations where the information they need to do their job is either very simple or can be discovered from the built-in application framework. For example, I found them useful for accessing localized resources, application settings, or the current UI language.