Created
September 8, 2017 23:50
-
-
Save aboveaboutbelow/a08cbc8fbd13ae8b23dd4c1d92453597 to your computer and use it in GitHub Desktop.
WPF ListBox with SelectedIndices property
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.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