2011-12-15 39 views
3

我有一個屬性活動添加到WPF控制器,當屬性值改變

public sealed partial class Computer 
{ 
    private bool _online; 
    public bool Online 
    { 
     get { return _online; } 
     set 
     { 
      _online = value; 
      RaiseProperty("Online"); 
     } 
    } 
} 

這引發了類型INotifyPropertyChanged的事件

public sealed partial class Computer : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

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

我的問題是,我怎麼可以添加額外的事件,告訴在這種情況下,TabControl每次在線屬性更改時都會運行特定的方法?

回答

3

您需要的方法註冊到PropertyChanged事件

MyComputer.PropertyChanged += Computer_PropertyChanged; 

void Computer_PropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    if (e.PropertyName == "Online") 
    { 
     // Do Work 
    } 
} 
+1

天哪,這是令人尷尬的簡單:o – Verzada 2011-12-16 09:49:09

+3

如果您將使用這個解決方案,看http://george.softumus.com/?p=32 - 有解決方案如何防止在您的代碼中使用「魔術字符串」(如「在線」) – chopikadze 2011-12-16 10:02:57

0
public sealed partial class Computer 
{ 
    // This event is fired every time when Online is changed 
    public event EventHandler OnlineChanged; 

    private bool _online; 
    public bool Online 
    { 
     get { return _online; } 
     set 
     { 
      // Exit if online value isn't changed 
      if (_online == value) return; 

      _online = value; 
      RaiseProperty("Online"); 

      // Raise additional event only if there are any subscribers 
      if (OnlineChanged != null) 
       OnlineChanged(this, null); 
     } 
    } 
} 

您可以使用此事件,如:

Computer MyComputer = new MyComputer(); 
MyComputer.OnlineChanged += MyComputer_OnlineChanged; 

void MyComputer_OnlineChanged(object sender, EventArgs e) 
{ 
    Computer c = (Computer)c; 
    MessageBox.Show("New value is " + c.Online.ToString()); 
}