Wpf enterprise application data verification and wpf enterprise application verification
In wpf, IDataErrorInfo is used for data verification. The bound object must implement this interface and add ValidatesOnDataErrors = True to the UI binding expression. In this way, when data verification occurs, wpf calls the index in this interface and returns the corresponding verification information. We add an attribute trigger for the control to respond to the verification.
The following describes some of the code in my project. For specific effects, see several common business scenarios in enterprise-level development of wpf.
UI binding
<TextBox Text="{Binding EditProduct.Num, ValidatesOnExceptions=True,ValidatesOnDataErrors=True,NotifyOnValidationError=True}" Grid.Column="1"/>
IDataErrorInfo implementation in model
Public string this [string columnName] {get {switch (columnName) {case "Num": if (Num. HasNothing () return "No. cannot be blank"; if (! OnLogicValidate ("Num") return "number cannot be repeated"; if (Num. length> 100) return "the Length cannot exceed 100 characters"; break;} return string. empty ;}}
To transfer logical verification to ViewModel, I specifically designed an event in the base class of the model. The OnLogicValidate method will execute this event, for example, I used it in ViewModel, in this way, complicated logic verification is transferred to the VM, while the model only retains simple logic such as length verification and type verification.
bool EditProduct_PropertyNeedLogicValidate(string propertyName,Object model) { if (propertyName == "Num" && XDBContext.tb_product.FirstOrDefault(p => p.Num == EditProduct.Num && p.ID != EditProduct.ID) != null) return false; return true; }
Finally, add the property trigger to the control template to respond to errors. Note that you also need to set the binding property of the control to NotifyOnValidationError = True.
<Setter Property="Template"> <Setter.Value> <ControlTemplate> <ControlTemplate.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value></Setter>