WPF listbox : problem with selection
In my XAML file, I have a ListBox declared like this :
<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 that b开发者_JAVA百科inding directly displays the content of my collection.
But when I have several value that hold the same value (for example "10" six times), the selection in the ListBox has a weird behaviour : it select 2-3 elements instead of the only the one on which I clicked.
Moreover, when I click to another listBoxItem, it doesn't unfocus the previous selected one.
Then it is impossible to see which item is actually selected, and impossible to get the SelectedIndex value.
Has someone an idea?
The problem is that the listbox cannout distinguish between the different values. Therefore, once you click one of the "10"s, it sets it SelectedItem property and updates its presentation. Because it cannot distinguish between the value types it marks every "10" as selected.
But why do you have "10" several times in your listbox? If it is just the numeric value 10 or the string "10" it does not make any sense to me.
If you have a more complex model behind that and you just display one property, than you should bind the complex model and set the DisplayMemberPath instead.
C#
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
精彩评论