【问题标题】:TextBox in WPF and text formatWPF 和文本格式的文本框
【发布时间】:2014-02-17 03:14:23
【问题描述】:

我正在尝试创建一个 TextBox 控件并强制用户在此处仅输入特定格式的数字。

如何在 WPF 中做到这一点?

我在 TextBox 类中没有找到像“TextFormat”或“Format”这样的属性。

我制作了这样的 TextBox(不是在可视化编辑器中):

TextBox textBox = new TextBox();

我想要 MS Access 表单中的 TextBox 行为(例如,用户只能在该文本框中输入“000.0”格式的数字)。

【问题讨论】:

标签: c# wpf textbox


【解决方案1】:

考虑使用 WPF 的内置验证技术。请参阅有关 ValidationRule 类和此 how-to 的此 MSDN 文档。

【讨论】:

    【解决方案2】:

    您可能需要的是屏蔽输入。 WPF 没有,因此您可以自己实现它(例如,使用validation),或者使用可用的第三方控件之一:

    【讨论】:

      【解决方案3】:

      根据您的说明,您希望将用户输入限制为带小数点的数字。 您还提到您正在以编程方式创建 TextBox。

      使用 TextBox.PreviewTextInput 事件来判断字符的类型并验证 TextBox 内的字符串,然后在适当的地方使用 e.Handled 取消用户输入。

      这样就可以了:

      public MainWindow()
      {
          InitializeComponent();
      
          TextBox textBox = new TextBox();
          textBox.PreviewTextInput += TextBox_PreviewTextInput;
          this.SomeCanvas.Children.Add(textBox);
      }
      

      进行验证的肉类和土豆:

      void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
      {
          // change this for more decimal places after the period
          const int maxDecimalLength = 2;
      
          // Let's first make sure the new letter is not illegal
          char newChar = char.Parse(e.Text);
      
          if (newChar != '.' && !Char.IsNumber(newChar))
          {
              e.Handled = true;
              return;
          }
      
          // combine TextBox current Text with the new character being added
          // and split by the period
          string text = (sender as TextBox).Text + e.Text;
          string[] textParts = text.Split(new char[] { '.' });
      
          // If more than one period, the number is invalid
          if (textParts.Length > 2) e.Handled = true;
      
          // validate if period has more than two digits after it
          if (textParts.Length == 2 && textParts[1].Length > maxDecimalLength) e.Handled = true;
      }
      

      【讨论】:

      • 谢谢,但这不是我想要的。
      • @Kamil:你想用 XAML 做格式吗?更好地解释你想要什么......并意识到它会受到可能的限制:) 你所展示的只是一行代码,它只是实例化了一个 TextBox 控件。真的没什么好去的。
      • 我想要 MS Access 表单中的格式,(用户只能在该文本框中输入数字)。
      • 所以你想限制用户输入只允许数字,这是有道理的。请编辑您的问题并将其放入其中。
      • 这不仅仅是“只允许数字”。我希望它们采用特定格式(我想确定应该有多少小数位等)
      猜你喜欢
      • 2013-08-21
      • 2011-06-03
      • 1970-01-01
      • 2021-12-15
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多