Wpf combobox text if nothing marine is selected

ComboBox ItemsSource changed = & gt; SelectedItem is ruined

Unfortunately, when setting ItemsSource to a Selector object, SelectedValue or SelectedItem is immediately set to zero, even if the corresponding position is in new ItemsSource.

It doesn't matter whether you implement is Equals .. functions or you are using an implicitly comparable type for your SelectedValue.

Well, you can save SelectedItem / Value before setting ItemsSource and as a restore. But what if there is a binding on SelectedItem / Value it will be called twice:
set to zero
restore the original.

That takes the extra effort and also it can lead to some undesirable behavior.

Here is a solution that I made. For any switch object. Clearly only SelectedValue binding before setting ItemsSource.

UPD: Added try / finally to protect exception handlers, also added null check for binding.

Here is a XAML example:

Unit test

Here's a unit test case to prove it works. Just comment on that to see the test fail when using the standard bindings.

Shareimprove this answer norekhov