6
votes

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

Lets call the ListBoxes LB1 and LB2 for the time being, now when I click an item in LB1, I want the same item in LB2 to get selected automatically i.e if I select 3 items in LB1 using either Shift+Click or Ctrl+Click the same items in LB2 get selected.

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

2

2 Answers

10
votes

Place a SelectionChanged event on your first listbox

LB1.SelectionChanged += LB1_SelectionChanged;

Then implement the SelectionChanged method like so:

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

Did you try 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