簡體   English   中英

使用 C# 在列表框中選擇項目

[英]Selecting items in a listbox using C#

我在我的 WPF window 中使用了兩個相同的 ListBox 控件(相同 = 兩個 ListBox 的ItemSource相同,因此它們看起來相同)並且兩個 ListBoxes 上的選擇模式都設置為 Multiple。

讓我們暫時調用 ListBoxes LB1LB2 ,現在當我單擊LB1中的一個項目時,我希望自動選擇LB2中的相同項目,即如果我使用Shift + ClickCtrl +單擊LB1 中的 select 3 個項目LB2中的相同項目被選中。

已經挖掘了 Listbox 屬性,如SelectedItemsSelectedIndex等,但沒有運氣。

在您的第一個列表框上放置一個 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM