Accept only one comma in Textbox c # WPF

4

Hello, I'm using 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 stays like this

  

0, 00

And when he starts to write he writes like this

  

0.22,00

I'd like to take this, "00" right. I already tried to give TextBox.Text.Replace(",00","") but he keeps putting it.

    
asked by anonymous 13.12.2018 / 13:45

1 answer

1

It may be better to validate the value when entering text to avoid incorrect character input.

For this you should subscribe to the event PreviewTextInput :

<TextBox PreviewTextInput="PreviewTextInput" />

In method PreviewTextInput we 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;
}
    
13.12.2018 / 14:30