WPF listbox : problem with selection

与世无争的帅哥 提交于 2020-01-02 08:34:54

问题


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 binding 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?


回答1:


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



来源:https://stackoverflow.com/questions/1607074/wpf-listbox-problem-with-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!