Sync Multi Select Listbox with ViewModel
Today one of my colleagues at Infusion asked me how he could sync up the selection of a ListBox with his ViewModel. WPF supports already single mode selection via the ICollectionView yet when it comes to MultiSelect there is no out of the box support in WPF.
Attached Properties to the rescue …..
I quickly when in my VS and wrote up a simple Attached property that hooks to the SelectionChanged event of the ListBox and populates a list of selected items to the ViewModel.
This is how the attached property looks like
#region SelectedItems
/// <summary>
/// SelectedItems Attached Dependency Property
/// </summary>
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(ListBoxHelper),
new FrameworkPropertyMetadata((IList)null,
new PropertyChangedCallback(OnSelectedItemsChanged)));
/// <summary>
/// Gets the SelectedItems property. This dependency property
/// indicates ....
/// </summary>
public static IList GetSelectedItems(DependencyObject d)
{
return (IList)d.GetValue(SelectedItemsProperty);
}
/// <summary>
/// Sets the SelectedItems property. This dependency property
/// indicates ....
/// </summary>
public static void SetSelectedItems(DependencyObject d, IList value)
{
d.SetValue(SelectedItemsProperty, value);
}
/// <summary>
/// Handles changes to the SelectedItems property.
/// </summary>
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var listBox = (ListBox)d;
ReSetSelectedItems(listBox);
listBox.SelectionChanged += delegate
{
ReSetSelectedItems(listBox);
};
}
#endregion
private static void ReSetSelectedItems(ListBox listBox)
{
IList selectedItems = GetSelectedItems(listBox);
selectedItems.Clear();
if (listBox.SelectedItems != null)
{
foreach (var item in listBox.SelectedItems)
selectedItems.Add(item);
}
}
and here is how you would use it in the XAML
<ListBox ItemsSource="{Binding MyData}" Grid.Column="1" local:ListBoxHelper.SelectedItems="{Binding SelectedData}"
SelectionMode="Extended"/>As you can see all you have to set is the List you want to populate in the ViewModel and the rest is taken care of by the Attached Property.
Please Note: This code was implemented quickly without any testing
to prove an implementation idea, so please do review it before putting
it in production
| Attachment | Size |
|---|---|
| WpfApplication2.zip | 47.07 KB |
- Login or register to post comments
- 825 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)









