Wpf – How to prevent duplicates in a WPF Listbox control

duplicateslistboxwpf

I have a WPF listbox control that is declaratively bound to a textbox. The listbox's ItemsSource is an ObservableCollection that is built from an XML file. I can easily prevent duplicate entries in the listbox when a new item is added because I can check for it in the "Add" button's Click event handler.

However, when an existing item's value is changed in the textbox (which obviously shows the listbox's selected item) to one that already exists in the list I want to prevent this, but I don't know how.

I'd appreciate help with this!

Best Answer

You can create your own validation rule by deriving from ValidationRule and apply it to your text box's binding. In the Validate method you can check for duplicates and return a ValidationResult of false to prevent the binding source from being updated.

Related Topic