2010-12-14 48 views
0

這是我的視圖模型 -WPF,裝訂的datacontext

public class ViewModel 
{ 
    public ObservableCollection<Person> Persons { get; set; } 
} 

,這是類人:

public class Person : INotifyPropertyChanged 
{ 
    private string _firstName; 
    public string FirstName 
    { 
     get { return _firstName; } 
     set 
     { 
      _firstName = value; 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs("FirstName")); 
      } 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 

現在,每一次的人的名字中的一個改變我想要做一些任務, 可以說提出一個消息框。

我該怎麼做?

回答

1

您需要實現INotifyPropertyChanged

public class Person : INotifyPropertyChanged 
{ 
    private string firstName; 
    public string FirstName 
    { 
     get { return this.firstName;} 
     set 
     { 
      this.firstName = value; 
      this.RaisePropertyChanged("FirstName"); 
      MessageBox.Show("Hello World"); 
     } 
    } 
} 

public event PropertyChangedEventHandler PropertyChanged; 

protected void RaisePropertyChanged(string propertyName) 
{ 
    PropertyChangedEventHandler propertyChanged = this.PropertyChanged; 
    if ((propertyChanged != null)) 
    { 
     propertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
+1

您顯示MessageBox的方式與Binding/DataContext或INotifyPropertyChanged無關;我的猜測是OP正在尋找更多的屬性 – 2010-12-14 17:43:11

+0

@ Aaron的設置者中的MessageBox.Show(),哦,真的,亞倫,以及我看不出你如何解釋,「現在,每當其中一個人名字正在改變我想做一些任務,讓我們說舉一個消息框,我該怎麼做?「,任何其他方式。如果你有一些重要的想法,爲什麼不發表一個答案而不是你的意見。 – Gabe 2010-12-14 18:00:03

+0

如果問題不清楚,請向OP詢問更多信息。我只是簡單地指出來,或許你可以提供一個額外的路線來考慮這些因素。 – 2010-12-14 18:04:31

1

通常你的人類將使用的接口INotifyPropertyChanged的,發射PropertyChanged事件每當名字的變化。這使您可以將視圖中的項目綁定到Person類,並在數據更改時更新視圖。

要在任何FirstName時彈出消息框,但是您需要在視圖中隱藏一些代碼。一種方法是像以前一樣,只要調用改變FirstName的事件,就使用MessageBox.Show使用INotifyProperty更改並訂閱視圖中所有Person對象。您可以使用ObservableCollection中的CollectionChanged事件來跟蹤進出列表中的Person對象,以確保它們都連接到您的Person FirstName changed事件處理程序。

在我看來,最好的方法是在ViewModel中有一個事件,而不是在任何Person類(使用特定Person對象作爲參數)進行更改時觸發的Person類。這隻有在ViewModel是唯一可以改變Person.FirstName的東西時纔會起作用,並且View必須以適當的方式綁定到ViewModel才能生效。