Home > OS >  How to set a type for inputs wpf?
How to set a type for inputs wpf?

Time:09-10

I have a input and I want it to accept only the data type I want like string or double. Is there any way I can do it programmatically?

I tried

TextBox text = new TextBox();
text.Type = 'numberic'; // an input that only accepts int.
text.Type = 'double';//or like this.

My app is dynamic so I want it to s.th like this . More general for all data types. but it didn't work. I used to say type in html but here I don't know if there is way to do it or not in wpf?

CodePudding user response:

you can add on textChanged event to the text box and then handle the data changed

follow this example:

TextBox textBox = new TextBox();
textBox.TextChanged  = TextBox_TextChanged;

For int datatype:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        int iValue = -1;

        if (Int32.TryParse(textBox.Text, out iValue) == false)
        {
            TextChange textChange = e.Changes.ElementAt<TextChange>(0);
            int iAddedLength = textChange.AddedLength;
            int iOffset = textChange.Offset;
            textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);
            textBox.Select(textBox.Text.Length, textBox.Text.Length);
        }
    }

in the case you want another number datatype just change ivalue to float or double etc..

and then use float.tryparse or double.tryparse

I hope this can help.

  • Related