简体   繁体   中英

Setting the Default Value for Decimal Property in WPF Binding

I bound my WPF form to a class's property that is Decimal. The textbox automatically higlighted in red if the user enter invalid format (string instead of decimal). However, I want to make it more secure by validating before storing the inserted data into database.

The problem is, whenever a user enter a non decimal value, the binding will return 0 instead of null or error. So it managed to get into the database without second level validation.

What is the best way to validate a WPF binding to a decimal? Right now it wont return null so I do not have any means to capture the error.

Here is how I bound the textbox

        <TextBox x:Name="stockTxtBx" Grid.Row="3" Grid.Column="1"  Style="{StaticResource StandardBox}" Text="{Binding StockOnHand}"/>

Also, where can I modify to add a validation?

The problem is, whenever a user enter a non decimal value, the binding will return 0 instead of null or error

You are slightly incorrect in your above statement. What actually happens when a user enters some text that has an invalid type for a particular field is this:

  1. The invalid text causes a red border (or other decoration depending on the ErrorTemplate value) to appear around the TextBox
  2. The data bound property value remains at the last valid value that was entered

So, in your case, that last valid value may have been 0 , which is why you assumed that an invalid value would always return 0 . So in fact, only the invalid value is ignored, while the last valid value remains.

However, to improve this issue, you have several options. One way would be to check the value of the Validation.HasError Attached Property before you save the data. Obviously, if you detect that any errors are present, then you would popup a message to alert the user, rather than continuing to save. You can find out more about this method from the Binding Validation.HasError property in MVVM question.

Another option would be to restrict the textual input of a particular TextBox so that it would not be possible to enter non numeric keys. I won't go over the details on how to do this again here, instead preferring to request that you look at the answers to the Numeric Data Entry in WPF question, here on Stack Overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM