Search code examples
wpflistviewitemsource

How to update source of WPF ListView?


I have a WPF ListView to wich I bind my collection. Properties of the objects in this collection are changed in a background thread. I need to update ListView when properties are changed. SourceUpdated event is not fired when I change some object's property.

P.S. Setting ItemSource to null and rebinding then is not appropriate.


Solution

  • Make sure your object implements INotifyPropertyChanged and raises the required change notification when the setter is called on your property.

    // This is a simple customer class that 
    // implements the IPropertyChange interface.
    public class DemoCustomer  : INotifyPropertyChanged
    {
        // These fields hold the values for the public properties.
        private Guid idValue = Guid.NewGuid();
        private string customerNameValue = String.Empty;
        private string phoneNumberValue = String.Empty;
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    
        // The constructor is private to enforce the factory pattern.
        private DemoCustomer()
        {
            customerNameValue = "Customer";
            phoneNumberValue = "(555)555-5555";
        }
    
        // This is the public factory method.
        public static DemoCustomer CreateNewCustomer()
        {
            return new DemoCustomer();
        }
    
        // This property represents an ID, suitable
        // for use as a primary key in a database.
        public Guid ID
        {
            get
            {
                return this.idValue;
            }
        }
    
        public string CustomerName
        {
            get
            {
                return this.customerNameValue;
            }
    
            set
            {
                if (value != this.customerNameValue)
                {
                    this.customerNameValue = value;
                    NotifyPropertyChanged("CustomerName");
                }
            }
        }
    
        public string PhoneNumber
        {
            get
            {
                return this.phoneNumberValue;
            }
    
            set
            {
                if (value != this.phoneNumberValue)
                {
                    this.phoneNumberValue = value;
                    NotifyPropertyChanged("PhoneNumber");
                }
            }
      }
    }
    

    If you are instead referring to items being added/removed from the collection (which you did not mention) then you would need to make sure your collection is an ObservableCollection<T>