Kamil
Kamil

Reputation: 13931

TextBox in WPF and text format

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).

Upvotes: 1

Views: 4806

Answers (3)

Dmitriy Khaykin
Dmitriy Khaykin

Reputation: 5258

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

Upvotes: 0

Athari
Athari

Reputation: 34275

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:

Upvotes: 2

deloreyk
deloreyk

Reputation: 1239

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

Upvotes: 2

Related Questions