开发者

How can I prevent duplicates in a WPF Listbox control?

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 d开发者_开发问答uplicate 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!


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.


Listen to the CollectionChanged event and check when the collection has been modified if there are any duplicates and remove them.

Also, you can take a look at this question and its' answer for an observable collection that also notifies you when its' items' properties change.

Edit:

If you don't want to use the collection I mentioned above, you can make sure your collection's items implement INotifyPropertyChanged and every time you add an item to the collection, listen to its PropertyChanged event. In the handler, you check if the property that changes is the one that is displayed in the ListBox and check if any other element has the same value of this property. If you find such an element, you either change the value of your property to its old value, or remove the element entirely, it depends on the logic of your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜