none
Binding a ViewModel to ListBox SelectedItems

    Question

  • I am developing a UI using the Model-View-ViewModel pattern. I have a situation where I need to keep a list of SelectedItems in sync between a ListBox and my ViewModel class, and ideally I would like to do this without using code behind my XAML pages

    My first thought was to have a SelectedItems property which I bound using {Binding SelectedItems, Mode=OneWayToSource} so that the SelectedItems list in the List box could be picked up by my ViewModel, and then listened to there for changes (Reflector shows that SelectedItems is actually an instance of ObservableCollection). Problem with this approach is that since SelectedItems is read-only, this binding doesn't work, even though it is OneWayToSource.

    Does anybody have any other ideas? I was thinking along the lines of an attached property that I could add to my ListView.

    Friday, November 10, 2006 5:39 PM

Answers

  • Eric,
      Yes I did find an elegant solution, and I've just found time to write a blog post about it.

    What I did was to create an attached property, SynchronizedSelectedItems. You databind this to a SelectedItems property on your ViewModel, and then, with a bit of magic, the SelectedItems property on the ListBox and your SelectedItems property are kept in sync.
    The "magic" is a class which listens out for CollectionChanged events in either collection, and propagates the changes to the other.
    • Marked as answer by Samuel Jack Thursday, February 12, 2009 4:13 PM
    Thursday, February 12, 2009 12:44 PM

All replies

  • Hi Sam,

     

    Have hou found any elegant solution ?

    Monday, March 24, 2008 5:38 PM
  • Eric,
      Yes I did find an elegant solution, and I've just found time to write a blog post about it.

    What I did was to create an attached property, SynchronizedSelectedItems. You databind this to a SelectedItems property on your ViewModel, and then, with a bit of magic, the SelectedItems property on the ListBox and your SelectedItems property are kept in sync.
    The "magic" is a class which listens out for CollectionChanged events in either collection, and propagates the changes to the other.
    • Marked as answer by Samuel Jack Thursday, February 12, 2009 4:13 PM
    Thursday, February 12, 2009 12:44 PM