WPF uses IDataErrorInfo to implement data validation, binding entities need to implement this interface, and add Validatesondataerrors=true in UI binding expressions, so that when data validation occurs, WPF invokes the index in the interface and returns the appropriate checksum information, and we add property triggers for the control to respond to the checksum.
The following is a description of some of the code in my project, which is seen in several common business scenarios in WPF enterprise-level development.
UI Bindings
<textbox text="{Binding editproduct.num, validatesonexceptions=true,validatesondataerrors=true, Notifyonvalidationerror=true}" grid.column="1"/>
The implementation of IDataErrorInfo in model
Public string This[stringColumnName] { Get { Switch(columnName) { Case "Num": if(Num.hasnothing ())return "the number cannot be empty"; if(! Onlogicvalidate ("Num")) return "number cannot be duplicated"; if(Num.length > -) return "length cannot exceed 100 characters"; Break; } return string. Empty; }}
In order to transfer the logical checksum to ViewModel, I specifically designed an event in the model's base class, and the Onlogicvalidate method would execute the event, such as I used in ViewModel, so that more complex logic checks would be transferred to the VM. The model only retains the logic of simple length check, type checking, and so on.
BOOL Editproduct_propertyneedlogicvalidate (string Propertyname,object model) { if" Num"null"returnfalse; return true ; }
Finally, a property trigger is added to the control template to respond to the error, and note that you also need to set the control's binding property Notifyonvalidationerror=true
<setter property="Template"> <Setter.Value> <ControlTemplate> <ControlTemplate.Triggers> <trigger Pr operty="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>
Data validation for WPF enterprise applications