Accept only one comma in Textbox c# WPF

Asked

Viewed 267 times

4

Hello I have my decimal textbox like this:

      <TextBox x:Name="TextBox"  KeyDown="TextBox_KeyDown"  
        Style="{StaticResource MeuTextBoxValor}" Height="23" Margin="1"   
        Text="{Binding Peso,  NotifyOnValidationError=true,  StringFormat={}{0:#0.00##}, 
    ConverterCulture='pt-BR', 
UpdateSourceTrigger=PropertyChanged}" 
VerticalAlignment="Center" Width="120" />

When you put a comma in this field it gets like this

0,00

And when he starts writing he writes like this

0,22,00

I’d like to take that "." off to the right. I’ve tried to give a TextBox.Text.Replace(",00","") but he continues to put.

  • Try to change your StringFormat for {0:#,##0.00}.

  • Same thing João

1 answer

1


It may be better to validate the value when entering text, to avoid incorrect input of characters.

For this you must subscribe to the event PreviewTextInput:

<TextBox PreviewTextInput="PreviewTextInput" />

In the method PreviewTextInput validate the comma:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    bool approvedDecimalPoint = false;

    if (e.Text == ",")
    {
        if (!((TextBox)sender).Text.Contains(","))
            approvedDecimalPoint = true;
    }

    if (!(char.IsDigit(e.Text, e.Text.Length - 1) || approvedDecimalPoint))
        e.Handled = true;
}

  • He still keeps putting two commas.

  • Okay, I edited the answer to include a condition.

  • Still the same thing, because the e.Text will always be the comma. Even if I take from Textbox.Text it will still give one because not yet the comma.

  • Edited and reduced response. Before I put the e.Text wrongfully. It should be ((TextBox)sender).Text.

  • It worked now yes :-) that was right John

Browser other questions tagged

You are not signed in. Login or sign up in order to post.