Is it possible to trigger some event when something changes in a given class?
E.g. I have a class that has 100
fields and one of them is being modified externally or internally. Now I want to catch this event. How to do this?
The most I wonder if there is a trick to do this quickly for really extended classes.
Using Developer Tools. Go to the sources tab. Click on the Event Listener Breakpoints, on the right side. Then perform the activity that will trigger the event, i.e. click if the event that used is click, double click if it is dblclick event.
As a best practice, convert your public fields to manual properties and implement your class
with the INotifyPropertyChanged
interface
in order to raise a change event
.
EDIT: Because you mentioned 100 fields I would suggest you to refactor your code like in this great answer: Tools for refactoring C# public fields into properties
Here is an example of it:
private string _customerNameValue = String.Empty;
public string CustomerName
{
get
{
return this._customerNameValue;
}
set
{
if (value != this._customerNameValue)
{
this._customerNameValue = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Check this out: INotifyPropertyChanged Interface
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