使用 C# 选择列表框中的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/665273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:27:25  来源:igfitidea点击:

Selecting items in a listbox using C#

c#wpflistboxselection

提问by Anand Shah

I am using two ListBox controls in my WPF window that are identical (identical = ItemSourceof both the ListBox is same and so they look same) and the selection mode on both the ListBoxes is set to Multiple.

我在 WPF 窗口中使用了两个相同的 ListBox 控件(两个 ListBox 的相同 =ItemSource相同,因此它们看起来相同)并且两个 ListBox 上的选择模式都设置为 Multiple。

Lets call the ListBoxes LB1and LB2for the time being, now when I click an item in LB1, I want the same item in LB2to get selected automatically i.e if I select 3 items in LB1 using either Shift+Clickor Ctrl+Clickthe same items in LB2get selected.

让我们调用列表框LB1LB2暂时,现在当我点击一个项目LB1,我想在同一个项目LB2得到自动选择,即如果我选择LB1 3项使用任一Shift+ClickCtrl+Click在同一个项目LB2得到选择。

Have dug the Listbox properties like SelectedItems, SelectedIndexetc but no luck.

挖列表框的属性,如SelectedItemsSelectedIndex等,但没有运气。

采纳答案by Arcturus

Place a SelectionChanged event on your first listbox

在您的第一个列表框上放置一个 SelectionChanged 事件

LB1.SelectionChanged += LB1_SelectionChanged;

Then implement the SelectionChanged method like so:

然后像这样实现 SelectionChanged 方法:

void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LB2.SelectedItems.Clear();
    foreach(var selected in LB1.SelectedItems)
    {
        LB2.SelectedItems.Add(selected);
    }
}

回答by RvdK

Did you try SetSelected?

你试过 SetSelected 吗?

listBox2.SetSelected(1, True)

You can use it like this

你可以像这样使用它

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);
   }

use the selected items from LB1 as a index in LB2

使用从 LB1 中选择的项目作为 LB2 中的索引