-1

I have a TextBox which has a binding for a non-nullable decimal value. This is my XAML code below. I need the UpdateSourceTrigger and the ValidatesOnDataErrors=true.

<TextBox 
    Text="{Binding Quantity, StringFormat=f2, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
    />

The problem is that on the TextBox the values 0.00 is always displayed. When I start typing on the TextBox the 0.00 is always there. To get the values after the decimal, the next arrow keys should be used. When a decimal point is typed then the TextBox allows two decimal points but since the data annotations for the property is listed it shows an error and then we will have to hit the backspace button to clear the decimal zeros. How can I make the TextBox to show an empty string when the value is zero and when I start typing, the TextBox should accept the values that are typed in and not show the 0.00.

Vinshi
  • 313
  • 2
  • 7
  • 27
  • Your title doesn't match the rest of the question, `0 != null`. Please clarify. – H H Nov 02 '17 at 13:19
  • 1
    When you say "null", you mean "empty string", is that correct? – 15ee8f99-57ff-4f92-890c-b56153 Nov 02 '17 at 13:20
  • This may be your solution: https://stackoverflow.com/a/11478265/424129 – 15ee8f99-57ff-4f92-890c-b56153 Nov 02 '17 at 13:21
  • Yes, an empty string. When the textbox is not in focus and if the textbox is empty then the value should be 0.00. – Vinshi Nov 02 '17 at 13:22
  • To clarify the last comment: To do this with the standard WPF TextBox, you will have to write a lot of code modifying the control's behavior. It would be wiser to use a control designed for this purpose. – 15ee8f99-57ff-4f92-890c-b56153 Nov 02 '17 at 13:30
  • 1
    Usually I use a DataTrigger that binds the Text Property without formatting when `IsKeyboardFocusWithin = true`. That way it's formatted when not focused, or not formatted if you're entering data. You can find an example here : https://stackoverflow.com/a/8680879/302677 . And if you want to hide the 0.00, just add another trigger so if value = 0, Text is blank. – Rachel Nov 02 '17 at 15:07

1 Answers1

0

Without having tested this: You could use the GotFocus event or similar events and check if the current value is 0:

private void textbox1_GotFocus(Object sender, EventArgs e) {
    TextBox tb = (sender as TextBox);
    if(tb == null) return;

    decimal d = 0;
    if(Decimal.Parse(tb.Text, out d)) {
        if(d==0) tb.Text = String.Empty;
    }
}

Look at the PreviewX events too. E.g. PreviewKeyDown.

MrToast
  • 1,159
  • 13
  • 41