Skip to content

Instantly share code, notes, and snippets.

@aboveaboutbelow
Created September 8, 2017 23:50
Show Gist options
  • Save aboveaboutbelow/a08cbc8fbd13ae8b23dd4c1d92453597 to your computer and use it in GitHub Desktop.
Save aboveaboutbelow/a08cbc8fbd13ae8b23dd4c1d92453597 to your computer and use it in GitHub Desktop.
WPF ListBox with SelectedIndices property
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
public class MultiIndexedListBox : ListBox
{
public IList<int> SelectedIndices { get; private set; }
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
UpdateSelectedIndices();
base.OnSelectionChanged(e);
}
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
UpdateSelectedIndices();
base.OnItemsChanged(e);
}
private void UpdateSelectedIndices()
{
SelectedIndices = FindVisualChildren<ListBoxItem>(this).Select((item, index) => new {index, item.IsSelected})
.Where(item => item.IsSelected)
.Select(a => a.index).ToList();
}
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment