Home > Enterprise >  WPF ComboBox (with IsEditable) - Prevent selected item from being deleted when removed from the list
WPF ComboBox (with IsEditable) - Prevent selected item from being deleted when removed from the list

Time:06-21

I have a ComboBox with IsEditable set to true. If I type in a custom option and then reset the list of choices (or even remove all choices), the displayed text does not change. Which is exactly what I want. However if I select or type in an option that is on the list and then later remove that option from the list, the selected text gets reset to null or empty string. In this second instance I'd like the selected text to not change (essentially turn into a custom entry).

I tried using the SourceUpdated and setting Handled to true but the event doesn't trigger whether I try replacing it with a new ObservableCollection or calling Clear.

Additionally manually managing the value is problematic because of delayed events triggering on the control itself in response to the change. If I use the following code the control responds to the updated list (and resets the value) after everything has finished executing.

string holdValue = SelectedListString;
ListOptions.Clear();
SelectedListString = holdValue;

This is a "nice to have" so I'm hoping for a simple solution and can't use 3rd party libraries for it. Worst case I guess I can do some hacky change tracking that then prevents the value from being modified when the setter is called on the dependency property SelectedListString, but I was hoping for something simpler.

CodePudding user response:

You can bind your 'SelectedListString' property with 'Text' property of the 'ComboBox' like this

<ComboBox IsEditable="True"
          ItemsSource="{Binding ListOptions}"
          SelectedItem="{Binding SelectedListString}"
          Text="{Binding SelectedListString}"/>

And when you clear the list, you hold on the value manually like you did

string holdValue = SelectedListString;
ListOptions.Clear();
SelectedListString = holdValue;
  • Related