【问题标题】:Selecting items in a listbox using C#使用 C# 在列表框中选择项目
【发布时间】:2009-03-20 07:46:45
【问题描述】:

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

让我们暂时调用 ListBoxes LB1LB2,现在当我单击 LB1 中的一个项目时,我希望 LB2 中的相同项目自动被选中,即如果我在其中选择 3 个项目LB1 使用 Shift+ClickCtrl+Click LB2 中的相同项目被选中。

已经挖掘了 SelectedItemsSelectedIndex 等 Listbox 属性,但没有运气。

【问题讨论】:

    标签: c# wpf listbox selection


    【解决方案1】:

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

    【讨论】:

    • 您好,非常感谢您的帮助,您提供的代码 sn-p 就像一个魅力。最好的问候@nand
    • 没问题..很高兴我能帮上忙! :)
    【解决方案2】:

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

    【讨论】:

    • 您好 PoweRoy,感谢您的回复,但不幸的是 WPF 没有公开 Listboxes 的 SetSelected 属性。我尝试用谷歌搜索它(setselected),但找不到解决方案,因此这篇文章致以最诚挚的问候@nand
    猜你喜欢
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多