Last active
December 1, 2016 16:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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