TextBox in WPF and text format

徘徊边缘 提交于 2019-12-23 04:35:35

问题


Im trying to create a TextBox control and force user to enter only numbers in specyfic format there.

How can I do it in WPF?

I have not found any properties like "TextFormat" or "Format" in TextBox class.

I made TextBox like this (not in visual editor):

TextBox textBox = new TextBox();

I want TextBox behavior like in MS Access forms, (user can put only numbers in that textbox in "000.0" format for example).


回答1:


Consider using WPF's built in validation techniques. See this MSDN documentation on the ValidationRule class, and this how-to.




回答2:


What you probably need is a masked input. WPF doesn't have one, so you can either implement it yourself (by using validation, for example), or use one of available third-party controls:

  • FilteredTextBox from WPFDeveloperTools
  • MaskedTextBox from Extended WPF Toolkit
  • etc.



回答3:


Based on your clarification, you want to limit user input to be a number with decimal points. You also mentioned you are creating the TextBox programmatically.

Use the TextBox.PreviewTextInput event to determine the type of characters and validate the string inside the TextBox, and then use e.Handled to cancel the user input where appropriate.

This will do the trick:

public MainWindow()
{
    InitializeComponent();

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

Meat and potatoes that does the 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;
}


来源:https://stackoverflow.com/questions/21820093/textbox-in-wpf-and-text-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!