Category Archives: metro-ui

Managing multiple selection in View Model ( .net Metro style app)

I was into refactoring of some WPF code (of metro application) into MVVM design pattern that has heavily used code behind.

I was stumbled upon a requirement, to bind to Selected Items property of GridView.  There was a list view in snapped mode and grid view in other modes (full/fill).

Requirement:

All I was trying to do is below

  1. To define SelectedItems in ViewModel
  2. Bind GridView.ItemsSource, ListView.ItemsSource to Items
  3. Somehow bind SelectedItems of GridView and ListView to SelectedItems
  4. After step 3, hoping that any selection change in GridView should be reflected to ListView and vice versa.

Challenges:

Never faced this scenario before, I found following challenges

  1. SelectedItems property is read only, and cannot be set directly
  2. SelectedItems cannot be used for binding expression, hence cannot be retrieved in View Model
  3. WinRT has no support for Behaviors. (For some unknown reasons, I wanted to use Attached Behavior). Thankfully there exists WinRTBehaviors on codeplex.

Note – Behaviors are not supported in WinRT natively. WinRTBehaviors is an open source for providing behavior support. This library is excellent, and provides behavior extension, exactly similar to WPF framework.

Behavior outline

  1. Behavior name -> MultiSelectBehavior. It will target ListViewBase (why -> Base class that provides Multiple selection mechanism)
  2. Add SelectedItems Dependency property to Behavior. This property will track of selected items of associated UI Element (List view derived class is referred as UI Element from hereafter).
  3. Hookup SelectionChanged event of UI element in  OnAttached, OnDetached event of Behavior. In the OnSelectionChanged event, sync up the changes to SelectedItems (of Behavior). It will propatege UI selection changes to SelectedItems in MultiBehavior.
  4. In the Property changed callback of SelectedItems (in Behavior), listen to CollectionChanged of bound object. Propagate changes in CollectionChanged event to UI Element.
  5. Add Behavior to UI elements in XAML
  6. Define data binding from SelectedItems (in Behavior) to SelectedItems in view model.

Code walkthrough

ListView, GridView are inherited from ListViewBase. ListViewBase provides multiple selection mechanism (SelectedItems, SelectionMode properties).

MultiSelectBehavior class is defined that is targeting ListViewBase.


public class MultiSelectBehavior : Behavior

SelectedItems dependency property is created in MultiSelectBehavior class. It internally holds all the selected items in the ListViewBase derived class.

public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
 "SelectedItems",
 typeof(ObservableCollection</pre>
SelectionChanged event is hooked up in the Behavior


protected override void OnAttached()
 {
 base.OnAttached();
 AssociatedObject.SelectionChanged += OnSelectionChanged;
 }

protected override void OnDetaching()
 {
 base.OnDetaching();
 AssociatedObject.SelectionChanged -= OnSelectionChanged;
 }

When SelectionChanged is triggered on element, SelectedItems is populated. _selectionChangedInProgress flag indicates, the selection change is in process. If this flag is set, no further handling is done (as it would trigger to infinite loop and stackoverflow exception).

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
 if (_selectionChangedInProgress) return;
 _selectionChangedInProgress = true;
 foreach (var item in e.RemovedItems)
 {
 if (SelectedItems.Contains(item))
 {
 SelectedItems.Remove(item);
 }
 }

foreach (var item in e.AddedItems)
 {
 if (!SelectedItems.Contains(item))
 {
 SelectedItems.Add(item);
 }
 }
 _selectionChangedInProgress = false;
 }

Hook the collection change event of bound ObservableCollection. Propagate any change to List view base derived ui elements. This is done in PropertyChangedCallback handler.

 private static void PropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs args)
 {
 NotifyCollectionChangedEventHandler handler = (s, e) => SelectedItemsChanged(sender, e);
 if (args.OldValue is ObservableCollection<object>)
 {
 (args.OldValue as ObservableCollection<object>).CollectionChanged -= handler;
 }

if (args.NewValue is ObservableCollection<object>)
 {
 (args.NewValue as ObservableCollection<object>).CollectionChanged += handler;
 }
 }

private static void SelectedItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
 if (sender is MultiSelectBehavior)
 {
 var listViewBase = (sender as MultiSelectBehavior).AssociatedObject;

var listSelectedItems = listViewBase.SelectedItems;
 if (e.OldItems != null)
 {
 foreach (var item in e.OldItems)
 {
 if (listSelectedItems.Contains(item))
 {
 listSelectedItems.Remove(item);
 }
 }
 }

if (e.NewItems != null)
 {
 foreach (var item in e.NewItems)
 {
 if (!listSelectedItems.Contains(item))
 {
 listSelectedItems.Add(item);
 }
 }
 }
 }
 }
 

MultiSelectBehavior is now completed.

Apply the behavior to UI elements.
Import the namespaces in XAML ( i -> behavior framework library, custom -> MultiSelectBehavior class)

 xmlns:i ="using:WinRtBehaviors"
 xmlns:custom="using:WinRtExt.Behavior"

Add behavior, and attach bind SelectedItems of behavior to SelectedItems of ViewModel


<i:Interaction.Behaviors>
 <custom:MultiSelectBehavior SelectedItems="{Binding SelectedItems, Mode=TwoWay}">

 </custom:MultiSelectBehavior>
 </i:Interaction.Behaviors>

Following XAML is for 2 controls (one list view, other grid view)


<GridView SelectionMode="Multiple" ItemsSource="{Binding Items}" BorderBrush="White" BorderThickness="2" ItemTemplate="{StaticResource textBlockDataTemplate}">
 <i:Interaction.Behaviors>
 <custom:MultiSelectBehavior SelectedItems="{Binding SelectedItems, Mode=TwoWay}">

 </custom:MultiSelectBehavior>
 </i:Interaction.Behaviors>
 </GridView>
 <Rectangle Width="20"></Rectangle>
 <ListView SelectionMode="Multiple" ItemsSource="{Binding Items}" BorderBrush="White" BorderThickness="2" ItemTemplate="{StaticResource textBlockDataTemplate}">
 <i:Interaction.Behaviors>
 <custom:MultiSelectBehavior SelectedItems="{Binding SelectedItems, Mode=TwoWay}">
 </custom:MultiSelectBehavior>
 </i:Interaction.Behaviors>
 </ListView>

Both list view and grid view are multi select enabled and in sync. Any selection change in any control is propagated to other control.

MultiselectSample is attached code. (Rename extension from doc to zip. It is a wordpress limitation).

The code is written in VS2012 RC in Win 8 Release preview. (It is incompatible with older versions, Win 8 Consumer preview, Win 8 developer preview, and may get broken in future versions).

Advertisements