WPF List: Choice Issue

In my XAML file, I have a ListBox declared as follows:

<ListBox x:Name="lstDeck" Height="280" ItemsSource="{Binding Path=Deck}" > <ListBox.ItemTemplate> <DataTemplate> <ListBoxItem Content="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

In my view model, Deck is an ObservableCollection, so the binding directly displays the contents of my collection.

But when I have several values ​​that have the same value (for example, "10" six times), the choice in the ListBox has a strange behavior: it selects 2-3 elements, not just the one I clicked on.

Also, when I click on another listBoxItem, it does not focus the previous selected one.

Then it is impossible to see which element is actually selected, and it is impossible to get the value SelectedIndex.

Does anyone have an idea?

+3
source share
1 answer

The problem is that listbox cannout distinguishes between different values. Therefore, as soon as you press one of the "10", it sets the SelectedItem property and updates its presentation. Since it cannot distinguish between types of values, it marks each selected β€œ10”.

But why do you have β€œ10” several times on your list? If it's just a numeric value of 10 or the string "10", it makes no sense to me.

If you have a more complex model and just show one property, you must bind the complex model and set DisplayMemberPath instead.

WITH#

 public class Model { public Guid Id { get; set; } public string Value { get; set; } } 

Xaml

 <ListBox ItemsSource="{Binding Path=Models}" DisplayMemberPath="Value" /> <ListBox ItemsSource="{Binding Path=Models}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Value}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

Best regards - Oliver Hanappi

+8
source

All Articles