C# NumericUpDown.OnValueChanged, how it was changed?

天涯浪子 提交于 2019-12-14 03:58:47

问题


I would like to ask how to make custom EventArgs for existing event handler.

Lets say, that I have NumericUpDown numericUpDown control and I want handler for its OnValueChanged event. Double clicking to ValueChanged in visual studio makes snippet like this

private void numericUpDown_ValueChanged(object sender, EventArgs e)
{

}

However, I'd like to know how it was changed (like +5, -4.7), but plain EventArgs does not have this information. Maybe Decimal change = Value - Decimal.Parse(Text) would do the trick (because of delayed text change), but that's ugly way and may not work every single time.

I guess I should make my own EventArgs like this

class ValueChangedEventArgs : EventArgs
{
    public Decimal Change { get; set; }
}

and then somehow override NumericUpDown.OnValueChanged event to generate my EventArgs with proper information.


回答1:


It may be much easier to just tag the last value.

    private void numericUpDown1_ValueChanged(object sender, EventArgs e) {
        NumericUpDown o = (NumericUpDown)sender;
        int thisValue = (int) o.Value;
        int lastValue = (o.Tag == null) ? 0 : (int) o.Tag;
        o.Tag = thisValue;
        MessageBox.Show("delta = " + (thisValue - lastValue));
    }



回答2:


You would have to create your own numeric up down control that extends the .net version, define a delegate type for your event and then hide the base controls event property.

Delegate:

public delegate void MyOnValueChangedEvent(object sender, ValueChangedEventArgs args);

Event Args Class:

class ValueChangedEventArgs : EventArgs
{
    public Decimal Change { get; set; }
}

New NumericUpDown class, hide the inherited event with 'new':

public class MyNumericUpDown : NumericUpDown
{
    public new event MyOnValueChangedEvent OnValueChanged;
}

Look here for instructions on how to raise your custom event, and here for additional information on event handling.



来源:https://stackoverflow.com/questions/25938227/c-sharp-numericupdown-onvaluechanged-how-it-was-changed

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