Reputation: 10146
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.
Upvotes: 7
Views: 3767
Reputation: 13003
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
Upvotes: 13