Binding GridView.SelectedItems property

I tried to find a way to bind GridView’s SelectedItems property to a ViewModel’s property. As we know, the property is read only so there is no DependencyProperty for it. Finding a workaround which made it possible to bind to it turned out to be a quite difficult task.

Using Attached Properties (didn’t work)

My first approach was creating a class called GridViewHelper which contained attached property which would have helped me bind to the SelectedItems property. The problem I had was that when the owner type of the property was GridViewHelper, my breakpoint in property changed callback never fired. And when the owner type was just GridView, the breakpoint fired but as a result I got the actual Binding object instead of the results of the binding, which would have been some objects from my ViewModel.

So this was my first approach which didn’t work:

Using WinRtBehaviors library (works!)

I continued searching for a working solution or tips to create a working solution. I stumbled upon CodeProject which seemed to have a great solution using Behaviors. WinRT doesn’t support behaviors natively but awesome people behind WinRtBehaviors library (also available via NuGet) have created behaviors for WinRT.

The solution in CodeProject is good but not perfect, at least not to my needs. I don’t like the fact that I’m forced to use object as the type of ObservableCollection as in my ViewModels everything is typed to their actual types. And because of generic variance issues I can’t cast ObservableCollection<MyType> to ObservableCollection<object>. Also there seemed to be a bug in the solution: when I cleared the collection in my ViewModel the View still had items selected.

So after a bit of tweaking, here is the solution I’m using at the moment.

Base class (from CodeProject with support for Clear() and Type parameter)

Examples how to derive it:

How to use it in XAML:

 

, , , , ,

About Janne Rautiola

I'm a software developer at Sebitti Oy. I began learning programming in 2007 at Oulu University of Applied Sciences and at the moment my focus is on WinRT.

Trackbacks/Pingbacks

  1. Windows Store Developer Links – 2012-12-10 | Dan Rigby - 10.12.2012

    [...] Windows 8 JavaScript games, Space Cadet and Catapult Wars, to the leaderboard service…”Binding GridView.SelectedItems property (Janne Rautiola)“I tried to find a way to bind GridView’s SelectedItems property to a [...]

Vastaa