繁体   English   中英

更新NumericUpDown控件的值,而不会引发ValueChanged事件(Winforms)

[英]Update Value of the NumericUpDown control without raising of ValueChanged event (Winforms)

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

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上尝试了它-找到了所有事件处理程序)。

您是否尝试过仅更改内部值并更新文本? 这样,您可以绕过被触发的事件处理程序。

如果您查看源代码( 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();
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM