Reputation: 733
say I have an int Index = 0;
. This value may be changed by the user at any point of the program. When it does, I need to update all my screens to data concerned with that new index value. I have a function for this I just need help figuring out how to call it.
My idea is to create a timer, and on every tick event it checks to see if the value of my variable Index
has changed. If yes then execute my function. But this seems really amateur to me. There has to be something more direct correct? I heard of something called "INotifyPropertyChanged" or something like that but I'm having a hard time finding a solid example of how it works.
Any ideas are much appreciated thank you.
Upvotes: 1
Views: 330
Reputation: 6744
You can use an event and subscribe to it then in the handler call the method. You will create the event like so:
public event IndexChangedEventHandler IndexChanged;
public delegate void IndexChangedEventHandler(int newValue);
protected virtual OnIndexChanged(int newValue)
{
if (IndexChanged != null)
IndexChanged(newValue);
}
Then use a property to wrap your index field and call the event inside of it:
private int _index;
public int Index
{
get
{
return _index;
}
set
{
_index = value;
OnIndexChanged(value);
}
}
Then all you would need do to is subscribe to the event like:
IndexedChanged += new IndexChangedEventHandler(IndexChanged_EventHandler);
private void IndexChanged_EventHandler(int newValue)
{
//call your update method here
}
Upvotes: 7