如何使NumericUpDown只读

13

我希望能够使WinForms中的NumericUpDown控件不可编辑,或者至少禁用旋转控制。我尝试了将控件设置为只读,但使用鼠标滚轮数值仍在改变。请帮助我实现这一目标。

3个回答

21

尝试以下方法将数字上/下设置为只读:

numericUpDown1.ReadOnly = true;    
numericUpDown1.Increment = 0;

希望它有所帮助。


10

另一种选择是通过子类化NumericUpDown并重写DownButtonUpButton方法,在设置ReadOnly时提前返回:

public override void DownButton()
{
   if(this.ReadOnly)
      return;

   base.DownButton();
}

public override void UpButton()
{
   if(this.ReadOnly)
      return;

   base.UpButton();
}

这似乎也防止了向上/向下箭头按键和鼠标滚轮改变值。

这种方法的好处是,现在您可以在控件上数据绑定ReadOnly属性,并期望它使值只读,而不仅仅是文本区域。


1
另一种选择:NumericUpDown控件有两个子控件,"UpDownButtons"和"UpDownEdit"。我们想要禁用第一个:
numericUpDown1.ReadOnly = true;
numericUpDown1.Controls[0].Enabled = false; // Controls[0] is the spinner

或者将Controls[0].Visible设置为false,以完全隐藏它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接