简体   繁体   English

WPF中的自定义NumericUpDown ValueChanged事件

[英]Custom NumericUpDown ValueChanged event in WPF

Since WPF doesn't contain a NumericUpDown control as known from WinForms , I implemented my own and take care of upper and lower value bounds as well as other validation. 由于WPF不包含WinForms已知的NumericUpDown控件,因此我实现了自己的控件,并处理上限和下限值以及其他验证。

Now, the WinForms NumericUpDown held a ValueChanged event which would be nice to implement it too. 现在, WinForms NumericUpDown举行了一个ValueChanged事件,它也很适合实现它。 My question is: How can I lift the TextChangedEvent of a TextBox to my main application? 我的问题是:如何将TextBoxTextChangedEvent提升到我的主应用程序? Delegate s? Delegate Or are there any other preferred ways to implement this? 或者还有其他任何首选方式来实现这一点吗?

I would personally prefer to use a delegate for this purpose, as I can set my own input parameters for it. 我个人更喜欢为此目的使用delegate ,因为我可以为它设置我自己的输入参数。 I would do something like this: 我会做这样的事情:

public delegate void ValueChanged(object oldValue, object newValue);

Using object as the data type would allow you to use different numerical types in the NumericUpDown control, but then you'd have to cast it to the correct type each time... I'd find this a bit of a pain, so if your control would only use one type, int for instance, then you could change your delegate to this: 使用object作为数据类型将允许您在NumericUpDown控件中使用不同的数字类型,但是每次你必须将它NumericUpDown转换为正确的类型...我会发现这有点痛苦,所以如果你的控件只会使用一种类型,例如int ,然后你可以将你的delegate更改为:

public delegate void ValueChanged(int oldValue, int newValue);

Then you would need a public property for users of the control to attach handlers: 然后,您需要一个公共属性,以便控件的用户附加处理程序:

public ValueChanged OnValueChanged { get; set; }

Used like so: 像这样使用:

NumericUpDown.OnValueChanged += NumericUpDown_OnValueChanged;

...

public void NumericUpDown_OnValueChanged(int oldValue, int newValue)
{
    // Do something with the values here
}

Of course, that's no good unless we actually call the delegate from inside the control and let's not forget to check for null in case no handler has been attached: 当然,除非我们实际从控件内部调用委托,否则不要忘记在没有附加处理程序的情况下检查null

public int Value
{ 
    get { return theValue; }
    set
    { 
        if (theValue != value)
        {
            int oldValue = theValue;
            theValue = value;
            if (OnValueChanged != null) OnValueChanged(oldValue, theValue);
            NotifyPropertyChanged("Value"); // Notify property change
        }
    }
}

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

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