[英]Selecting items in a listbox using C#
我在我的 WPF window 中使用了两个相同的 ListBox 控件(相同 = 两个 ListBox 的ItemSource
相同,因此它们看起来相同)并且两个 ListBoxes 上的选择模式都设置为 Multiple。
让我们暂时调用 ListBoxes LB1
和LB2
,现在当我单击LB1
中的一个项目时,我希望自动选择LB2
中的相同项目,即如果我使用Shift + Click或Ctrl +单击LB1 中的 select 3 个项目LB2
中的相同项目被选中。
已经挖掘了 Listbox 属性,如SelectedItems
、 SelectedIndex
等,但没有运气。
在您的第一个列表框上放置一个 SelectionChanged 事件
LB1.SelectionChanged += LB1_SelectionChanged;
然后像这样实现 SelectionChanged 方法:
void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LB2.SelectedItems.Clear();
foreach(var selected in LB1.SelectedItems)
{
LB2.SelectedItems.Add(selected);
}
}
您尝试过 SetSelected 吗?
listBox2.SetSelected(1, True)
你可以像这样使用它
private void DoLB2Selection()
{
// Loop through all items the ListBox.
for (int x = 0; x < listBox1.Items.Count; x++)
{
// Determine if the item is selected.
if(listBox1.GetSelected(x) == true)
// Deselect all items that are selected.
listBox2.SetSelected(x,true);
}
使用从 LB1 中选择的项目作为 LB2 中的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.