WPF列表框:选择问题 [英] WPF listbox : problem with selection

查看:256
本文介绍了WPF列表框:选择问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的XAML文件中,我有一个这样声明的ListBox:

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>

在我的视图模型中,Deck是一个ObservableCollection,因此绑定直接显示我的集合的内容.

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

但是,当我有多个具有相同值的值(例如,"10"代表六次)时, 列表框中的选择具有一种奇怪的行为:它选择2-3个元素,而不是我单击的唯一元素.

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.

此外,当我单击另一个listBoxItem时,它不会使之前选择的焦点失去焦点.

Moreover, when I click to another listBoxItem, it doesn't unfocus the previous selected one.

然后就看不到实际选择了哪个项目,也就无法获得SelectedIndex值.

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

有人有主意吗?

推荐答案

问题是列表框无法区分不同的值.因此,一旦单击"10"之一,它将设置其SelectedItem属性并更新其表示.由于无法区分值类型,因此将每个"10"标记为选中.

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.

但是,为什么列表框中多次出现"10"呢?如果它只是数字值10或字符串"10",对我来说就没有任何意义.

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.

如果您在其后有一个更复杂的模型,而只显示一个属性,则应该绑定该复杂模型并设置DisplayMemberPath.

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>

最好的问候
奥利弗·哈纳皮(Oliver Hanappi)

Best Regards
Oliver Hanappi

这篇关于WPF列表框:选择问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆