Reputation: 494
I have a property
public sealed partial class Computer
{
private bool _online;
public bool Online
{
get { return _online; }
set
{
_online = value;
RaiseProperty("Online");
}
}
}
Which raises an event of type 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));
}
}
}
My question is, how can I add an additional event telling in this case an TabControl to run a specific method each time the Online Property changes?
Upvotes: 4
Views: 8213
Reputation: 4239
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);
}
}
}
You can use this event like:
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());
}
Upvotes: 1
Reputation: 132558
You need to register a method to the PropertyChanged
event
MyComputer.PropertyChanged += Computer_PropertyChanged;
void Computer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Online")
{
// Do Work
}
}
Upvotes: 4