2012-04-06 19 views

回答

2

您可以爲一個TextBox

<Style x:Key="TextBoxWithValidation" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> 
    <Setter Property="Validation.ErrorTemplate" Value="{StaticResource TextBoxValidationTemplate}"/> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="Background" Value="{StaticResource BackgroundValidationBrush}"/> 
      <Setter 
       Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Mode=Self}, 
       Path=(Validation.Errors)[0].ErrorContent)}" 
      /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

凡BackgroundValidationBrush會說粉紅色做這樣的事情。

請注意,在沒有錯誤的情況下,ToolTip綁定到(Validation.Errors)[0] .ErrorContent的常見解決方案將導致大量調試問題(技術術語),所以最好使用類似轉換器這樣的:

[ValueConversion(typeof(ReadOnlyObservableCollection<ValidationError>), typeof(string))] 
public class ValidationErrorsToStringConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, 
     CultureInfo culture) 
    { 
     var errors = value as ReadOnlyObservableCollection<ValidationError>; 

     // If there are no errors then return an empty string. 
     // This prevents debug exception messages that result from the usual Xaml of "Path=(Validation.Errors)[0].ErrorContent". 
     // Instead we use "Path=(Validation.Errors), Converter={StaticResource ValidationErrorsConverter}". 
     if (errors == null) 
     { 
      return string.Empty; 
     } 

     var errors2 = errors.Select(e => e.ErrorContent).OfType<string>().ToArray(); 

     return errors.Any() ? string.Join("\n", errors2) : string.Empty; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, 
     CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

和我們可以使用

<converters:ValidationErrorsToStringConverter x:Key="ValidationErrorsConverter"/> 

<!-- Style to be used as the base style for all text boxes --> 
<Style x:Key="TextBoxWithValidation" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> 
    <Setter Property="Validation.ErrorTemplate" Value="{StaticResource TextBoxValidationTemplate}"/> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="Background" Value="{StaticResource BackgroundValidationBrush}"/> 
      <Setter 
       Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Mode=Self}, 
       Path=(Validation.Errors), 
       Converter={StaticResource ValidationErrorsConverter}}" 
      /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 
+0

我只看到傳遞給我的一個轉換器的錯誤信息,即使一個以上的ViewModel's.GetErrors(「屬性名」)存在...想法? – gap 2016-06-23 20:32:32

0

我想你尋找的東西,像

Data Validation

能否使用sniplet:

<Binding.ValidationRules> 
    <DataErrorValidationRule/> 
</Binding.ValidationRules> 

定義的驗證規則,並在出現故障的情況下,你會得到一個紅色矩形 角落找尋相關的控制。

相關問題