There is probably a simple answer to this but I can't seem to find it. I have a textbox on my window that is two way bound to a decimal property. I have string format = N2 to ensure valid input. Here is my xaml:
<TextBox x:Name="tbxAmount"
Text="{Binding ItemAmount, StringFormat=N2, Mode=TwoWay}"
HorizontalAlignment="Left"
Height="23" .....
Validation works great - if an invalid input then the textbox is outlined in red and the property in the bound class is not changed. But...
There is a SAVE button that then saves changes made to the class properties to my database. Somehow in the SAVE button-click event I need to recognized that my textbox had invalid input and therefore prevent the database update. There must be a property indicating the format error on my textbox that i can reference, or something else I need to do to prevent the save?
All of these answers are great. The Validation class put me on the right track for solving this the way that works best for me at the moment.
In my Save click event I currently run a verify function in my item class that returns a series of messages if there are any verification errors. Then if the messages are not blank I display the error messages instead of proceeding with the save function.
So all I needed to do was check the result of GetHasError for tbx amount and included another error message if it was true. Here is the relevent code from my Click event... (Code in VB, save the ";"s)
Private Sub btnSave_Click(sender As Object, e As RoutedEventArgs) Handles btnSave.Click
Dim tErrors As String = ""
'validate
tErrors = sInvoiceItem.InvoiceItemVerify()
If Validation.GetHasError(tbxAmount) = True Then
tErrors = tErrors + "The amount entered must be a valid number." + Environment.NewLine
End If
If tErrors = Nothing Then ' proceed with save
....
So the key for me was the Validation.GetHasError() function. Thanks to all for your input.
In future, I'd like to work more with the solutions above from ViVi and qqww2 to keep the validation within XAML, however I'm not sure how to add to this the display of a message/feedback to the user.
Likewise the response above from Robert resolves the issue of preventing invalid data from being saved, yet I wouldn't want to have the item class itself issuing messages to the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With