這篇博客將介紹如何使用IDataErrorInfo進行數據校驗。下面直接看例子。一個Customer類,兩個屬性(FirstName, Age)
class Customer {public string FirstName{get;set;}public int Age{get;set;} }
將Customer類繼承IDataErrorInfo,并實現它的屬性。
class Customer : System.ComponentModel.IDataErrorInfo{public string this[string columnName]{get{string result = string.Empty;if(columnName == "FirstName"){if(string.IsNullOrWhiteSpace(FirstName)){result = "Name cannot null or empty.";}}else if(columnName == "Age"){if(Age < 0){result = "Age cannot less then zero.";}}return result;}}public string Error{get{return null;}}public string FirstName{get;set;}public int Age{get;set;}}
在UI中綁定Customer的FirstName,Age屬性,并且當出現錯誤數據時觸發驗證。
<Window.Resources><local:Customer x:Key="CustomerInstance" FirstName="Sam Bent" Age="24" /><ControlTemplate x:Key="TextBoxErrorTemplate"><Grid><Border BorderBrush="Blue" BorderThickness="1"><AdornedElementPlaceholder/></Border></Grid></ControlTemplate></Window.Resources><StackPanel Margin="10"><TextBox Text="{Binding Source={StaticResource CustomerInstance}, Path=FirstName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"Validation.ErrorTemplate="{x:Null}"Margin="0,5" /><TextBox Text="{Binding Source={StaticResource CustomerInstance}, Path=Age, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}"> <TextBox.Style><Style TargetType="{x:Type TextBox}"><Style.Triggers><Trigger Property="Validation.HasError" Value="True"><Setter Property="Background" Value="Red" /><Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /></Trigger></Style.Triggers></Style></TextBox.Style></TextBox></StackPanel>
將Customer的FirstName與Age屬性分別綁定在兩個TextBox中,設置ValidatesOnDataErrors=True來觸發驗證。將錯誤信息綁定在TextBox的ToolTip屬性上,
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" 或者
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"或者
<Style TargetType="{x:Type TextBox}"><Style.Triggers><Trigger Property="Validation.HasError" Value="True"><Setter Property="Background" Value="Red" /><Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /></Trigger></Style.Triggers> </Style>
另外可以對ErrorTemplate進行定制,例如上面代碼中的TextBoxErrorTemplate。
運行結果:
代碼點擊這里下載,感謝您的閱讀。