Obtenga todos los elementos seleccionados en ListBox (incluidos los duplicados)

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, Siempre consigo 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>

código:

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. Seleccione ambos Apples y volverá 1. Select an Apple y Pear, volverá 2.

preguntado el 03 de julio de 12 a las 23:07

ListBox.GetSelectedIndices() possibly? -

Thanks, but that method doesn't exist in Silverlight. My post was edited to include the 'asp.net' tag, but this is not asp.net. -

Ah, I didn't know that about silverlight. I was looking at the C# tag. Try this: stackoverflow.com/questions/3836313/… -

No, unfortunately that foreach loop only goes round once because it considers any duplicates as just one item rather than separate ones. -

That is really weird that the ListBox cares in the element are the same. WHere did you SelectedItems returns only the first distinct element? -

2 Respuestas

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.

Respondido 05 Jul 12, 00:07

When you add two string with same value Listbox will treat them same. Better you create a custom class Like

class Composit { public string Key{get;set;} public string Value{get;set;} }

Bind the list with this class. This way if you set Apple to two object but key is different you will get correct result

Cheers! Vinod

Respondido 05 Jul 12, 09:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.