代码之家  ›  专栏  ›  技术社区  ›  Greg D

如何强制子类文本框的值?

  •  0
  • Greg D  · 技术社区  · 14 年前

    像很多人一样,我需要在wpf中创建一个数字文本框控件。到目前为止,我已经取得了很好的进展,但我不确定下一步的正确做法是什么。

    作为控件规范的一部分,它必须 总是 显示一个数字。如果用户高亮显示所有文本并点击backspace或delete,则需要确保该值设置为零,而不是“blank”。在wpf控件模型中,应如何执行此操作?

    到目前为止(缩写):

    public class PositiveIntegerTextBox : TextBox
    {
        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            // Ensure typed characters are numeric
        }
    
        protected override void OnPreviewDrop(DragEventArgs e)
        {
            // Ensure the dropped text is numeric.
        }
    
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            if (this.Text == string.Empty)
            {
                this.Text = "0";
                // Setting the Text will fire OnTextChanged again--
                // Set Handled so all the other handlers only get called once.
                e.Handled = true; 
            }
    
            base.OnTextChanged(e);
        }
    
        private void HandlePreviewExecutedHandler(object sender, ExecutedRoutedEventArgs e)
        {
            // If something's being pasted, make sure it's numeric
        }
    }
    

    一方面,这很简单,似乎工作正常。但我不确定它是否正确,因为我们总是(如果有那么简单的话)在将文本重置为零之前将其设置为空白。不过,没有previewTextChanged事件允许我在值更改之前对其进行操作,所以这是我的最佳猜测。

    对吗?

    1 回复  |  直到 14 年前
        1
  •  0
  •   Aaron McIver    14 年前

    为什么不简单地利用你的 OnPreviewTextInput 处理程序检查传入值是否为int,尝试转换它…

    Convert.ToInt32(e.Text);
    

    如果转换失败,则它不是int,因此将其标记为handled,这样文本就不会更改。

    虽然这可能会稍微违反您的需要,例如…删除所有文本不会还原为0,但它仍然是int。我个人认为,从ui的角度来看,这更符合逻辑,因为清除所有输入会将值移动到0?它本身就定义了 TextBox 作为接受非int值,因为ui在这些条件下发生更改。

    推荐文章