Skip to content

Instantly share code, notes, and snippets.

@owen2
Last active December 1, 2016 16:12
Show Gist options
  • Save owen2/36a0d34dc847833b820d to your computer and use it in GitHub Desktop.
Save owen2/36a0d34dc847833b820d to your computer and use it in GitHub Desktop.
Bind to all of the SelectedItems in a ListBox set to multiple select mode.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace WPFStuff
{
public static class ListBoxExtension
{
public static IList GetSelectedItems(DependencyObject obj)
{
return (IList)obj.GetValue(SelectedItemsProperty);
}
public static void SetSelectedItems(DependencyObject obj, IList value)
{
obj.SetValue(SelectedItemsProperty, value);
}
// Using a DependencyProperty as the backing store for SelectedItems. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(ListBoxExtension), new PropertyMetadata(Setup));
private static void Setup(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Prevent duplicate event handlers
if (e.OldValue != null)
((Selector)d).SelectionChanged -= SelectionChanged;
var items = e.NewValue as IList ?? new object[0];
// To sync up initial values
foreach (var item in items)
(d as ListBox).SelectedItems.Add(item);
((Selector)d).SelectionChanged += SelectionChanged;
}
static void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var items = GetSelectedItems(sender as DependencyObject);
if (items == null)
return;
foreach (var item in e.RemovedItems)
items.Remove(item);
foreach (var item in e.AddedItems)
items.Add(item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment