Selecting items in a list using C #

I use two ListBox controls in my WPF window that are identical (identical = ItemSource both ListBox are the same, and therefore they look the same), and in select mode both ListBoxes are set to Multiple.

Lets call ListBoxes LB1 and LB2 for now, when I click an item in LB1 , I want the same item in LB2 be obtained automatically, i.e. if I select 3 elements in LB1 using either Shift + Click or Ctrl + Click , the same elements in LB2 will be selected.

Dug Listbox properties like SelectedItems , SelectedIndex , etc., but no luck.

+6
c # wpf listbox selection
source share
2 answers

Put the SelectionChanged event on your first list

 LB1.SelectionChanged += LB1_SelectionChanged; 

Then we implement the SelectionChanged method as follows:

 void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e) { LB2.SelectedItems.Clear(); foreach(var selected in LB1.SelectedItems) { LB2.SelectedItems.Add(selected); } } 
+9
source share

Have you tried 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 selected items from LB1 as an index in LB2

0
source share

All Articles