I'm looking to fire an event each time a property within my class is SET. I'd like to be able to trigger this same event whenever one of my properties are set. I have (around 12 of them)
I.e.
public class MyClass
{
private int _myHeight;
private int _myWidth;
public int myHeight
{
get { return myHeight; }
set { myHeight = value;
//This fires event!
}
}
public int myWidth
{
get { return myWidth; }
set { myWidth = value;
//This will fire the same event!
}
I'm not new to events themselves, but rather new to creating events. I've always used the 'out of the box' events that are used in windows apps. Any ideas?
Using INotifyPropertyChange
is the right approach (because it is a widely used type in .NET, so anybody can understand what your intent is). However, if you just want some simple code to start with, then the implementation of your class might look like this:
public class MyClass
{
private int _myHeight;
public event EventHandler Changed;
protected void OnChanged() {
if (Changed != null) Changed(this, EventArgs.Empty);
}
public int myHeight
{
get { return myHeight; }
set {
myHeight = value;
OnChanged();
}
}
// Repeat the same pattern for all other properties
}
This is the most straightforward way to write the code (which may be good for learning and bad for larger real-world applications).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With