C# – How to update a listview item that is bound to a collection in WPF

cdata-bindinglistviewnetwpf

In WPF, I have a ListView bound to an ObservableCollection in the code-behind. I have working code that adds and removes items from the list by updating the collection.

I have an 'Edit' button which opens a dialog and allows the user to edit the values for the selected ListView item. However, when I change the item, the list view is not updated. I'm assuming this is because I'm not actually adding/removing items from the collection but just modifying one of its items.

How do I tell the list view that it needs to synchronize the binding source?

Best Answer

You need to implement INotifyPropertyChanged on the item class, like so:

class ItemClass : INotifyPropertyChanged
{
    public int BoundValue
    {
         get { return m_BoundValue; }
         set
         {
             if (m_BoundValue != value)
             {
                 m_BoundValue = value;
                 OnPropertyChanged("BoundValue")
             }
         }
    }

    void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    int m_BoundValue;
}