Wednesday, April 30, 2014

Sorting Evolution (8) - Sorting a WPF ListView/GridView by clicking on the header - Behaviors (Expression Blend)

Eighth generation

Last time (Seventh Generation) we used Attached Properties to enable sorting within XAML. An alternative, but similar approach is Behaviors (Blend for VS2013, Working with Behaviors) from Expression Blend.

To create a custom Behavior (VS2013) the Behavior class is extended. Therefore we need to add a Reference to the Extension Assembly System.Windows.Interactivity from Blend SDK (for VS2013). To extend the Behavior<T> "using System.Windows.Interactivity" is added.

SortingAttached (Seventh Generation) is replaced by SortingBehavior. This leads to a reduction of code:

public class SortingBehavior : Behavior<ListView>
    private Sorting _sorting;
    public SortingBehavior()
        _sorting = new Sorting();
    protected override void OnAttached()
                        new RoutedEventHandler(OnColumnHeaderClicked));
    protected override void OnDetaching()
                        new RoutedEventHandler(OnColumnHeaderClicked));
    private void OnColumnHeaderClicked(object sender, RoutedEventArgs e)
        ListView listView = sender as ListView;
        if (listView == null)
        _sorting.Sort(e.OriginalSource, listView.Items);

There is no need to introduce a DependencyProperty. Instead we have the overridden methods OnAttached and OnDetaching. These methods add or remove the event handler (OnColumnHeaderClicked) that is executed if the column header is clicked. The method OnColumnHeaderClicked is nearly the same as in the Seventh Generation, but we do not need explicitly create and remember a Sorting object, because each ListView gets its own SortingBehavior object, where in the last sample (Seventh Generation) all ListViews have used the identical SortingAttached object.

In the XAML part of the View we need to add the namespace that leads to System.Windows.Interactivity from Blend SDK (for VS2013).


Furthermore we remove the Attached Property and set the Behavior.

<ListView x:Name="EighthResultData"
          ItemsSource="{Binding EighthResultData}">
        <sort:SortingBehavior />
            <GridViewColumn DisplayMemberBinding="{Binding ResultNumber}">
                <GridViewColumnHeader Content="Number"
                                      HorizontalContentAlignment="Left" />
            <GridViewColumn DisplayMemberBinding="{Binding ResultOutput}">
                <GridViewColumnHeader Content="Output"
                                      HorizontalContentAlignment="Left" />

The source code can be downloaded from

Further Posts

  1. Sorting a WPF ListView/GridView by clicking on the header
  2. Sort Direction Indicators 
  3. Sort in ViewModel 
  4. Sort Direction Indicators with Adorners
  5. Reusability
  6. More Reusability
  7. Attached Property
  8. Behaviors (Expression Blend)

No comments:

Post a Comment