以编程方式在列表框中选择项目/索引 [英] Programmatically selecting Items/Indexes in a ListBox

查看:89
本文介绍了以编程方式在列表框中选择项目/索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,我想设置System.Windows.Controls.ListBox的选定索引

到目前为止,我发现的最好的方法是从控件中删除所有项目,插入选定的对象,调用SelectAll(),然后插入其余的对象,但是这种解决方案在我的情况下既不起作用,也不是很有效. /p>

那么,如何设置以编程方式选择要在列表框中选择的项目?

解决方案

执行此操作的一种方法是将Selected字段添加到数据对象.然后,您需要覆盖默认的listboxitem样式,并将isselected属性绑定到对象中的Selected属性.然后,您只需要遍历数据项并更新选定值"即可.

如果您没有将Selected属性实现为依赖项属性,则需要您的类设置INotifyPropertyChanged接口,并在设置该值时引发propertychanged事件.

In WPF, I'd like to set the selected indexes of a System.Windows.Controls.ListBox

I best way I've found so far is to remove all the items from the control, insert the selected, call SelectAll(), then insert the rest, but this solution neither works in my situation nor is very efficient.

So, how do you set items in a Listbox to be selected, programmatically?

解决方案

One way you can do this is to add a Selected field to your data object. Then you need to overide the default listboxitem style and bind the isselected property to the Selected property in your object. Then you just need to go through your data items and update the Selected value.

If you don't implement that Selected property as a dependency property, you need your class to implented the INotifyPropertyChanged interface and raise the propertychanged event when you set the value.

这篇关于以编程方式在列表框中选择项目/索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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