views:

6801

answers:

2

Hi, 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 lisbox properties like selecteditems, selectedindex etc but no luck.

Any help is appreciated.

Best Regards,

@nand

A: 

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

PoweRoy
Hi PoweRoy,Thanks for the reply, but unfortunately WPF does not expose the SetSelected property for Listboxes. I tried googling for it (setselected) but couldn't get a solution and hence this postBest Regards@nand
Anand
+5  A: 

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);
    }
}
Arcturus
Hi There,Thank you very much your help is appreciated, the code snippet you gave works like a charm.Best Regards@nand
Anand
No problem.. glad I could help! :)
Arcturus