value changed eventhandler

心不动则不痛 提交于 2019-12-08 02:53:22

问题


I want to react, whenever an integer value has changed. So, is there a possibility to write an own eventhandler? I need to get the old value and the new one, because I have to de-reference some events for an object in a list with the index of the old value and reference these events to the listitem with the index of the new value.

Something like this (really abstract):

value.Changed += new Eventhandler(valuechanged);
private void valuechanged(object sender, eventargs e)
{
     list[e.Oldvalue] -= some eventhandler;
     list[e.newValue] += some eventhanlder;
}

Thanks.


回答1:


You can do something like this:

class ValueChangedEventArgs : EventArgs
{
     public readonly int LastValue;
     public readonly int NewValue;

     public ValueChangedEventArgs(int LastValue, int NewValue)
     {
         this.LastValue = LastValue;
         this.NewValue = NewValue;
     }
}

class Values
{
     public Values(int InitialValue)
     { 
          _value = InitialValue;
     }

     public event EventHandler<ValueChangedEventArgs> ValueChanged;

     protected virtual void OnValueChanged(ValueChangedEventArgs e)
     {
           if(ValueChanged != null)
              ValueChanged(this, e);
     }

     private int _value;

     public int Value
     {
         get { return _value; }
         set 
         {
             int oldValue = _value;
             _value = value;
             OnValueChanged(new ValueChangedEventArgs(oldValue, _value));
         }
     }
}

So you can use your class like here (Console Test):

void Main()
{
     Values test = new Values(10);

     test.ValueChanged += _ValueChanged;

     test.Value = 100;
     test.Value = 1000;
     test.Value = 2000;
}

void _ValueChanged(object sender, ValueChangedEventArgs e)
{
     Console.WriteLine(e.LastValue.ToString());
     Console.WriteLine(e.NewValue.ToString());
} 

This will print:

Last Value: 10
New Value:  100

Last Value: 100
New Value: 1000

Last Value: 1000
New Value: 2000



回答2:


The only things that comes close is the INotifyPropertyChanged andINotifyPropertyChanging interfaces. These define the PropertyChanged & PropertyChanging events respectively.

However, these won't give you the new or old value, just that it has changed/changing.

You typically define them on properties.. ala:

private int _myInt;
public int MyInt
{
    get
    {
        return this._myInt;
    }

    set
    {
        if(_myInt == value)
            return;

        NotifyPropertyChanging("MyInt");    
        this._myInt = value;
        NotifyPropertyChanged("MyInt");
        }
    }
}

Note: NotifyPropertyChanging() & NotifyPropertyChanged() are just private methods that invoke the events.



来源:https://stackoverflow.com/questions/9963809/value-changed-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!