在WPF中,我想要设置 System.Windows.Controls.ListBox 的选定索引。目前我找到的最佳方式是从控件中移除所有项,插入选定项,调用 SelectAll(),然后插入其余项,但这种解决方案在我的情况下不起作用,也不是非常高效。那么,如何以编程方式设置 ListBox 中的项目为选定状态呢?
你可以使用SelectedItems集合来设置多个选中的项目。这不是按索引而是按绑定的内容进行的:
foreach (var boundObject in objectsBoundToListBox)
{
ListBox.SelectedItems.Add(boundObject);
}
你可以通过向数据对象添加一个选中字段来实现这一点。然后,需要覆盖默认的列表框项样式,并将isselected属性绑定到对象中的Selected属性。接下来,只需遍历数据项并更新Selected值即可。
如果你不将Selected属性实现为依赖属性,则需要让你的类实现INotifyPropertyChanged接口,并在设置值时引发propertychanged事件。
ListBoxObject.SelectedItem = ListBoxObject.Items.GetItemAt(itemIndex);
这里的itemIndex是您想要选择的项。如果您想要选择多个项,则需要使用ListBox.SelectedIndexCollection属性。
您可以对多个部分执行此操作:
ListBoxObject.SelectedItems.Add(ListBoxObject.Items.GetItemAt(i));
其中 i 表示项目索引。
public class ProjectListItem : DependencyObject{
public Boolean IsChecked
{
get { return (Boolean)this.GetValue(CheckedProperty); }
set { this.SetValue(CheckedProperty, value); }
}
public static readonly DependencyProperty CheckedProperty =
DependencyProperty.Register("IsChecked", typeof(Boolean), typeof(ProjectListItem),
new PropertyMetadata(false));
}
foreach (var boundObject in objectsBoundToListBox)
{
ListBox.SelectedItems.Add(boundObject);
}