在不引发ValueChanged事件的情况下更新NumericUpDown控件的值(Winforms)

时间:2016-08-21 11:25:27

标签: c# winforms

我需要在不提高ValueChanged事件(WinForms,C#)的情况下更新NumericUpDown控件的值。
简单的方法是删除事件处理程序,如:

numericUpDown.ValueChanged -= numericUpDown_ValueChanged;

之后设置所需的值:

numericUpDown.Value = 15;

再次添加事件处理程序:

numericUpDown.ValueChanged += numericUpDown_ValueChanged;

问题是我想编写一个方法,将NumericUpDown控件作为第一个参数,需要的值作为第二个参数,并将按照下面给出的方式更新值。
为此,我需要为ValueChanged事件找到连接的事件处理程序(对于每个NumericUpDown,它不同)。
我搜索了很多,但没有找到对我有用的解决方案 我的最后一次尝试是:

private void NumericUpDownSetValueWithoutValueChangedEvent(NumericUpDown control, decimal value)
{
    EventHandlerList events = (EventHandlerList)typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField).GetValue(control);
    object current = events.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField)[0].GetValue(events);
    List<Delegate> delegates = new List<Delegate>();
    while (current != null)
    {
         delegates.Add((Delegate)GetField(current, "handler"));
         current = GetField(current, "next");
    }
    foreach (Delegate d in delegates)
    {
         Debug.WriteLine(d.ToString());
    }
}
public static object GetField(object listItem, string fieldName)
{
    return listItem.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField).GetValue(listItem);
}

运行NumericUpDownSetValueWithoutValueChangedEvent函数后,object current等于null,因此找不到任何一个EventHandler(我在Form上尝试过它 - 找到所有事件处理程序)。

1 个答案:

答案 0 :(得分:3)

您是否尝试过更改内部值并更新文本?这样你就可以绕过被解雇的事件处理程序。

如果您看一下源代码(http://referencesource.microsoft.com/System.Windows.Forms/winforms/Managed/System/WinForms/NumericUpDown.cs.html#0aaedcc47a6cf725) 您将看到属性Value正在使用名为currentValue的私有字段,这是您要设置的值。然后再做control.Text = value.ToString();

实施例

private void SetNumericUpDownValue(NumericUpDown control, decimal value)
{
    if (control == null) throw new ArgumentNullException(nameof(control));
    var currentValueField = control.GetType().GetField("currentValue", BindingFlags.Instance | BindingFlags.NonPublic);
    if (currentValueField != null)
    {
        currentValueField.SetValue(control, value);
        control.Text = value.ToString();
    }
}

这还没有经过测试,但我很确定它会起作用。 :) 快乐的编码!

相关问题