How do I update an existing element of an ObservableCollection?
Asked Answered
K

3

5

I have an instance of ObservableCollection bound to a WPF listbox with two separate data templates (one for display, one for editing). The data template for editing has a one-way binding on the textbox, and a Save button.

What changes do I need to make so that when I press the Save button (after putting the list item in edit mode), the value I change the textbox to replaces the value in the ObservableCollection (and the display)?

Koran answered 28/4, 2009 at 22:27 Comment(0)
N
9

Items in your collection should be of type that implements INotifyPropertyChanged interface. This way your list box will be notified that property value in your single item object has changed. ObservableCollection raises CollectionChanged event only when collection changes (items added, removed, etc.)

Quote from the MSDN library article on ObservableCollection

To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.

Numerous answered 29/4, 2009 at 5:44 Comment(2)
Thanks for answering. I'll try this out and see what happens.Koran
I implemented the INotifyPropertyChanged interface on my collection items as you suggested. That and changing the bindings from OneWay to TwoWay seems to have addressed my issue.Koran
O
1

For change notification to occur in a binding between a bound client and a data source, your bound type should either:

  • Implement the INotifyPropertyChanged interface (preferred).
  • Provide a change event for each property of the bound type.

Do not do both.

Source: MSDN: INotifyPropertyChanged Interface

Overtake answered 29/4, 2009 at 12:0 Comment(0)
O
1

I've solved similar problem using BindingList<T> class.

It has ListChanged event fired both on collection and individual item change.

Introduced in .Net 3.5

Ophthalmitis answered 27/2, 2011 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.