我有一个属性
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运行特定方法?
答案 0 :(得分:3)
您需要在PropertyChanged
事件
MyComputer.PropertyChanged += Computer_PropertyChanged;
void Computer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Online")
{
// Do Work
}
}
答案 1 :(得分: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());
}