There is an application on WPF, it has two ListBox . I need to make it so that when selecting any item in one of the ListBox , the selection is reset from the other and vice versa.

I tried to hang the SelectionChanged event on each one and SelectedIndex = -1 , but it turned out crazy, because the event (of course) was triggered by both ListBox , which led to a drop in the selection of both (after having to re-select)

In general, I ask for your help in resolving this issue!

    2 answers 2

    The easiest is probably this:

     void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { ListBox orig = (ListBox)sender; if (orig.SelectedItems.Count == 0) // выделения нет return; ListBox other = (sender == FirstListBox) ? SecondListBox : FirstListBox; other.UnselectAll(); } 
    • Yes thank you. Your option came up as it should. - EvgeniyZ
    • @EvgeniyZ: Please! - VladD

    Alternatively, you can use the switch operator, based on the fact that in WPF controls have names.

     switch ((sender as ListBox).Name) { case "listBox1": listBox2.SelectedIndex = -1; break; case "listBox2": listBox1.SelectedIndex = -1; break; } 
    • If this should be triggered by the SelectionChanged event, then a loop results, resulting in a reset of all selections. As I actually wrote above. Take for example, select something in the first ListBox and select after something in the second. Result: In the first one, the selection will disappear, and in the second one it won't even stand out (it’s necessary to be pressed a second time for selection) - EvgeniyZ