I have a ListBox that contains duplicate items. From what I gather, ListBox.SelectedItems will only return the first instance of a duplicate, but this causes problems when I want to perform an action on all items a user has selected. When I select multiple duplicates and call ListBox.SelectedItems.Count, I always get 1. Is there a way to get the indexes of all items, regardless if they’re unique or not? (ListBox mode is set to Multiple).
Added repro code demonstrating that the same item is considered a duplicate.
Xaml:
<Grid x:Name="LayoutRoot" Background="White">
<ListBox Height="288" HorizontalAlignment="Left" Margin="12,0,0,0" Name="listBox1" VerticalAlignment="Top" Width="276" SelectionMode="Multiple" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="313,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
code:
ObservableCollection<string> fruits = new ObservableCollection<string>();
fruits.Add("Apple");
fruits.Add("Pear");
fruits.Add("Orange");
fruits.Add("Apple");
listBox1.ItemsSource = fruits ;
I just wired up a button event to this:
MessageBox.Show(listBox1.SelectedItems.Count.ToString());
Select the top Apple and click the button, it will return 1. Select both Apples and it will return 1. Select an Apple and Pear, it will return 2.
I’ve added a GUID property in my class and randomised it before adding to the ObservableCollection. User doesn’t see the GUID, but the ListBoxItem is still considered unique and it now works. I’ll leave this question open for a bit incase someone knows of a solution that doesn’t require modifying the class unnecessarily.