Form Validation in WPF
I have been working with WPF and the MVVM pattern for a while now. I'm having difficulty getting validation working in a "normal" way:
1) I'm implement the IDataErrorInfo interface in my ViewModel. The XAML looks something like:
<TextBox Grid.Column="1"
Grid.Row="1"
Text="{Binding Path=ProjectKey, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />
The problem here is that whether LostFocus and PropertyChanged triggers are used, the textbox is validated before the user ever tabs to that control. This means if I'm validating empty fields, the user will see a whole lot of red when they first open the form. Ideall开发者_如何转开发y the input would only be validated after the first “lost focus” or “property change”, or once the "Submit" button is clicked.
2) The other issue is validation at the end when the user clicks "Submit". There are certain things you want to validate right before submitting to the database, such as duplicates. I understand I can use UpdateSourceTrigger=Explicit and call the UpdateSource method on all controls. I'm wondering if there is an appropriate way to do this within the MVVM pattern. It seems like such code shouldn't be in the ViewModel since it's very View specific...
Any ideas would be great. I've searched a lot online but can't seem to find the right solution...
For number one your properties on the ViewModel should be initialized with a value before hand in the constructor
public double Property1 {get; set;}
public ViewModel()
{
Property1 = 0;
}
For number two the submit button should not be enabled until all fields pass validation. If you have a field that is unique in the database then validate it on property change and display and error if it doesn't pass. You can have a boolean property that is bound to the button's IsEnabled property and set it to true once all fields pass validation.
精彩评论