【问题标题】:Padleft on numericupdownPadleft 上 numericupdown
【发布时间】:2017-12-08 02:30:17
【问题描述】:

我想在我的应用程序中使用 numericupdown 控件。我很清楚我可以改用纯文本框,但我更喜欢这个特定控件的 UI 适合我在应用程序中所做的方式。

根据所需的文本输出,它还需要在左侧有 0。如果我没记错的话,标准 numericupdown 控件不支持此功能。它的长度不应超过 4 位。但是,如果我输入更多,它必须对新的击键表示支持,并改为删除最左边的数字。向上和向下箭头应根据通常的行为增加/减少值。即使在键入值之后。

永远不应该允许它运行负数。它应该只接受整数。不过,这很容易通过 stock 功能处理。

【问题讨论】:

  • 目前格式的问题更适合codereview.stackexchange.com。如果您想将其保留在 stackoverflow 中,请编辑帖子并提出问题,然后发布您自己的答案。那么它对功能阅读器会更有用。
  • 不知道 codereview。谢谢你提到它。我会继续这样做。

标签: c# winforms numericupdown


【解决方案1】:

为可能关注的其他人发布部分答案。部分是在寻找我不是白痴的保证。

请注意,此 hack 取决于在提取最终值之前触发 Sync()。计时器会很快触发,但不能保证事情会以正确的顺序发生。在提取值之前立即手动触发 Sync() 可能没有什么坏处。

public class UpDownWith0 : System.Windows.Forms.NumericUpDown
{

  private System.Windows.Forms.Timer addzeros = new System.Windows.Forms.Timer();

  public UpDownWith0()
  {
    this.addzeros.Interval = 500; //Set delay to allow multiple keystrokes before we start doing things
    this.addzeros.Stop();
    this.addzeros.Tick += new System.EventHandler(this.Sync);
  }

  protected override void OnTextBoxTextChanged(object source, System.EventArgs e)
  {
    this.addzeros.Stop(); //reset the elapsed time every time the event fires, handles multiple quick proximity changes as if they were one
    this.addzeros.Start();
  }

  public void Sync(object sender, System.EventArgs e)
  {
    int val;
    this.addzeros.Stop();
    if (this.Text.Length > 4)
    {
      //I never want to allow input over 4 digits in length. Chop off leftmost values accordingly
      this.Text = this.Text.Remove(0, this.Text.Length - 4);
    }
    int.TryParse(this.Text, out val); //could use Value = int.Parse() here if you preferred to catch the exceptions. I don't.
    if (val > this.Maximum) { val = (int)this.Maximum; }
    else if (val < this.Minimum) { val = (int)this.Minimum; }
    this.Value = val; //Now we can update the value so that up/down buttons work right if we go back to using those instead of keying in input

    this.Text = val.ToString().PadLeft(4, '0'); //IE: display will show 0014 instead of 14
    this.Select(4, 0); //put cursor at end of string, otherwise it moves to the front. Typing more values after the timer fires causes them to insert at the wrong place
  }
}

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多