WPF Listview选择项目问题 [英] WPF Listview selecting item problem

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

问题描述

你好,
我在xaml中有这个listView:

Hello,
I have this listView in xaml:

<ListView Height="100" HorizontalAlignment="Left" Margin="32,196,0,0" Name="listView1" VerticalAlignment="Top" Width="438">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}"/>
        </GridView>
    </ListView.View>
</ListView>




我正在从代码中添加项目:




and i am adding items from code:

listView1.Items.Add(new {ID="item1", Description="item2" } );
listView1.Items.Add(new {ID="item3", Description="item4" } );
listView1.Items.Add(new {ID="item5", Description="item6" } );



问题是总是选择第一个项目,而我想选择其他项目,单击其他项目将不起作用,我该怎么办?



The problem is that always the first item is selected, and i want to select other items, clicking on other items wont work, what should i do?

推荐答案

使用自定义对象而不是无关紧要的.那应该解决.



You can use custom objects rather than annonomous. That should solve it.

i.e.

public class CustomListItem
{
    public string ID {get; set;}
    public string Description {get; set;}
}

...

listView1.Items.Add(new CustomListItem(){ID = "item1", Description="item2"};



另外,如果您希望选择特定项目,则可以保留该项目.



Also if you want a specific item to be selected you can then hold on to it.

CustomListItem _default = null;
...

_default = new CustomListItem(){ID = "item1", Description="item2"};
listView1.Items.Add(_default);

...
listView1.SelectedItem = _default;



仅供参考-原因是异常对象在堆栈上(我相信...我并未真正使用它们,但是行为导致了这一假设).通过创建自己的对象,它是基于引用的,因此,即使道具完全相同,它们也是不同的.直到重写Equals和HashCode为止,否则.



FYI - the reason being is that the annonomous objects are on the stack (I believe... I dont use them really but the behavior leads one to this assumption). By making your own object it is reference based so even if the props are the exact same, they are different. Until you override the Equals and HashCode to say otherwise.


我弄清楚了,就像OMG.

我不能在列表中包含相同的项目:

i figured it out, it''s like OMG.

i cant have the same items in the list:

listView1.Items.Add(new {ID="item1", Description="item2" } );

listView1.Items.Add(new {ID="item1", Description="item2" } );

listView1.Items.Add(new {ID="item1", Description="item2" } );

listView1.Items.Add(new {ID="item1", Description="item2" } );

listView1.Items.Add(new {ID="item1", Description="item2" } );



因为它将始终选择第一个.

如果我确实有相同的项目,有什么解决办法?



because it will always select the first one.

any solution if i do have the same items?


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

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