WPF和文本格式的TextBox

我试图创建一个TextBox控件并强制用户只输入specyfic格式的数字。

我怎么能在WPF中做到这一点?

我没有在TextBox类中找到任何属性,如“TextFormat”或“Format”。

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

TextBox textBox = new TextBox(); 

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

考虑使用WPF的内置validation技术。 请参阅ValidationRule类上的此MSDN文档以及此方法 。

你可能需要的是一个蒙面输入。 WPF没有,因此您可以自己实现(例如,通过使用validation ),或使用可用的第三方控件之一:

  • 来自WPFDeveloperTools的FilteredTextBox
  • Extended WPF Toolkit中的MaskedTextBox
  • 等等

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

使用TextBox.PreviewTextInput事件确定字符的类型并validationTextBox中的字符串,然后使用e.Handled取消适当的用户输入。

这样就可以了:

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

进行validation的肉和土豆:

 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; }