2010-11-22 71 views
0

我有一个WPF ListView到我绑定我的集合。该集合中对象的属性在后台线程中更改。当属性发生变化时,我需要更新ListView。当我更改某个对象的属性时,SourceUpdated事件不会被触发。如何更新WPF ListView的源代码?

P.S.将ItemSource设置为null并重新绑定然后不合适。

回答

2

确保你的对象实现INotifyPropertyChanged,并提出当设置器叫上你的财产所需的更改通知。

// 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"); 
      } 
     } 
    } 
} 

如果您是不是指的是被添加的项目/从集合(你没有提到)删除,那么你需要确保你的集合是一个ObservableCollection<T>

1

应该是自动的,你只需要使用一个ObservableCollection作为你的对象的容器,并且你的对象的类需要实现INotifyPropertyChanged(你可以为你想要通知列表视图的属性实现那个模式是一个变化)

MSDN