首页 文章

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

提问于
浏览
6

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

让我暂时调用ListBoxes LB1LB2 ,现在当我点击 LB1 中的项目时,我希望 LB2 中的相同项目自动被选中,即如果我使用Shift Click或Ctrl选择LB1中的3个项目点击相同的项目在 LB2 中被选中 .

挖了像 SelectedItemsSelectedIndex 等列表框属性,但没有运气 .

2 回答

  • 0

    在您的第一个列表框上放置一个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);
        }
    }
    
  • 9

    你尝试过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中的索引

相关问题