There is a form. Here is its contents
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <ListBox ItemsSource="{Binding Col1}" DisplayMemberPath="Name" SelectedValuePath="Sum" SelectedItem="{Binding Selected, Mode=TwoWay}"/> <ListBox Grid.Column="1" ItemsSource="{Binding Col2}" DisplayMemberPath="Name" SelectedValuePath="Sum" SelectedItem="{Binding Selected, Mode=TwoWay}" MouseDoubleClick="ListBox_MouseDoubleClick"/> </Grid>
Here is its background (it’s also a view)
public partial class MainWindow : Window, INotifyPropertyChanged { Output _selected; public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<Output> Col1 { get; set; } public ObservableCollection<Output> Col2 { get; set; } public Output Selected { get { return _selected; } set { _selected = value; OnPropertyChanged(nameof(Selected)); } } public MainWindow() { Col1 = new ObservableCollection<Output> { new Output {Name="name_1", Sum=1 }, new Output {Name="name_2", Sum=2 }, new Output {Name="name_3", Sum=3 }, new Output {Name="name_4", Sum=4 } }; Col2 = new ObservableCollection<Output> { Col1[2], Col1[3], new Output {Name="name_5", Sum=5 }, new Output {Name="name_6", Sum=6 } }; DataContext = this; InitializeComponent(); } private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) { Selected = null; } void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } }
I start, I select the first item in the left sheet. Everything's Alright. I select the last item in the left sheet (name 4). The corresponding item is highlighted in the second sheet. Now I select the last item in the second sheet ...
It was expected that in this case the selection will be removed in the left sheet, because this item is not in the linked collection. But the selection remains. Why?
UPD:
But the saddest thing turned out to be not even this, but the fact that when you move a tab on the sheets (or with a mouse, clicking on already selected visually items), the Selected property does not change. This will be seen if you attach a window title to it.
Title="{Binding Selected.Name}"
ListBox
and its “colleagues” do not behave very intuitively if the SelectedItem is attached to an item that is not in the list. - VladD