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

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

问题描述

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

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

到目前为止,我发现的最佳方法是从控件中删除所有项目,插入所选项目,调用 SelectAll(),然后插入其余项目,但这种解决方案既不适用于我的情况,也不是很有效.

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?

推荐答案

您可以这样做的一种方法是将 Selected 字段添加到您的数据对象.然后,您需要覆盖默认的 listboxitem 样式并将 isselected 属性绑定到对象中的 Selected 属性.然后你只需要检查你的数据项并更新 Selected 值.

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.

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

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天全站免登陆