C# WPF中的自定义NumericUpDown ValueChanged事件
由于WPF不包含从C# WPF中的自定义NumericUpDown ValueChanged事件,c#,wpf,winforms,events,user-controls,C#,Wpf,Winforms,Events,User Controls,由于WPF不包含从WinForms中已知的NumericUpDown控件,因此我实现了自己的,并负责上下限值以及其他验证 现在,WinFormsNumericUpDown保存了一个ValueChanged事件,实现它也很好。我的问题是:如何将TextBox的TextChangedEvent提升到我的主应用程序代表s?或者有其他更好的方法来实现这一点吗?我个人更愿意为此使用委托,因为我可以为它设置自己的输入参数。我会这样做: public delegate void ValueChanged(ob
WinForms
中已知的NumericUpDown
控件,因此我实现了自己的,并负责上下限值以及其他验证
现在,
WinForms
NumericUpDown
保存了一个ValueChanged
事件,实现它也很好。我的问题是:如何将TextBox
的TextChangedEvent
提升到我的主应用程序<代码>代表s?或者有其他更好的方法来实现这一点吗?我个人更愿意为此使用委托,因为我可以为它设置自己的输入参数。我会这样做:
public delegate void ValueChanged(object oldValue, object newValue);
使用object
作为数据类型将允许您在NumericUpDown
控件中使用不同的数字类型,但是每次都必须将其转换为正确的类型。。。我觉得这有点痛苦,所以如果控件只使用一种类型,例如int
,那么您可以将委托更改为:
public delegate void ValueChanged(int oldValue, int newValue);
然后,您需要一个公共属性,以便控件的用户附加处理程序:
public ValueChanged OnValueChanged { get; set; }
这样使用:
NumericUpDown.OnValueChanged += NumericUpDown_OnValueChanged;
...
public void NumericUpDown_OnValueChanged(int oldValue, int newValue)
{
// Do something with the values here
}
当然,除非我们实际上从控件内部调用委托,否则这是不好的,并且在没有附加处理程序的情况下不要忘记检查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
}
}
}
创建一个事件并在主应用程序中订阅它我认为您可以从纯WPF内容自定义一个NumericUpDown
,WPF
在System.Windows.Controls.Primitives
中有一个repeat按钮,只需添加更多的TextBox
和验证。你可以有一个更优雅的数字上下。搜索这些将帮助您获得一些示例