2010-11-22 72 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