[英]How to cancel the ValueChanged event for NumericUpDown controls?
在某些情況下,我想取消 Winforms 中NumericUpDown
控件的ValueChanged
事件(例如,當控件中設置的值相對於TextBox
中的另一個值太高時)。
但是,作為參數傳遞給NumericUpDown
控件的事件處理程序的EventArgs
不提供任何類似“取消”的功能,那么我該怎么做呢?
private void nudMyControl_ValueChanged(object sender, EventArgs e)
{
// Do some stuff, but only if the value is within a certain range.
// Otherwise, cancel without doing anything.
}
您可能可以通過使用Minimum
& maximum
屬性來處理這種情況,但也有一些解決方案。
一種方法是創建一個自定義控件,盡管這在我看來很糟糕。
public partial class CustomNumericUpDown : NumericUpDown
{
public CustomNumericUpDown()
{
InitializeComponent();
}
protected override void OnTextBoxKeyDown(object source, KeyEventArgs e)
{
if (MyCustomCondition())
{
e.Handled = true;
}
base.OnTextBoxKeyDown(source, e);
}
private bool MyCustomCondition()
{
var checkOut = false;
//if (something == foo)
//{
checkOut = true;
//}
return checkOut;
}
}
您還可以為ValueChanged
做一些事情:
這是一些虛擬示例,但您可以按照自己的方式進行更改:
public virtual decimal CurrentEditValue { get; internal set; } = 0M;
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (decimal.TryParse(Text, out decimal v))
{
CurrentEditValue = v;
OnValueChanged(e);
}
}
protected override void OnValueChanged(EventArgs e)
{
// if(CurrentEditValue == foo) Do_stuff.
base.OnValueChanged(e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.