0

我正在尝试在 WPF 中使用带有验证规则的数据绑定控件的验证输入。我有一posintValidationRule 堂课:

       public class posintValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        string _strInt = value.ToString();
        int _int = -1;
        if (!Int32.TryParse(_strInt, out _int))
            return new ValidationResult(false, "Value must be an integer");
        if (_int < 0)
            return new ValidationResult(false, "Value must be positive");
        return new ValidationResult(true, null);
    }
}

在 XAML 中还有一个样式错误模板:

   <Setter Property="Validation.ErrorTemplate">
     <Setter.Value>
        <ControlTemplate>
          <StackPanel>
            <Border BorderBrush="Red" BorderThickness="1" >
               <AdornedElementPlaceholder></AdornedElementPlaceholder>
            </Border>
            <TextBlock Text="there is an error"></TextBlock>
           </StackPanel>
         </ControlTemplate>
     </Setter.Value>
   </Setter>
  <Style.Triggers>
     <Trigger Property="Validation.HasError" Value="true">
        <Setter
            Property="ToolTip" 
            Value="{Binding RelativeSource={RelativeSource Self},
            Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>

发生验证错误时,ValidationResultfrom posintValidationRuleclass 的文本出现在工具提示中(“Value must be an integer”等)。

我怎么能在 TextBlock 中显示相同的文本Validation.ErrorTemplate,如果出现错误,现在会说:“有错误”?

4

2 回答 2

4

I have found the solution:

<Style TargetType="{x:Type TextBox}">
       <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
              <StackPanel>
                <Border BorderBrush="Red" BorderThickness="1" Margin="5,0,5,0" >
                    <AdornedElementPlaceholder Name="MyAdorner" ></AdornedElementPlaceholder>
                </Border>
                <TextBlock
                      Margin="5,0,0,0"
                      Foreground="Red" 
                      Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
               </TextBlock>
             </StackPanel>
           </ControlTemplate>
       </Setter.Value>
     </Setter>
</Style>

It works OK

于 2010-01-19T12:06:54.853 回答
0

DataContext 是(Validation.Errors),所以你可以这样做:

<Style TargetType="{x:Type TextBox}">
   <Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
        <ControlTemplate>
          <StackPanel>
            <Border BorderBrush="Red" BorderThickness="1" Margin="5,0,5,0" >
                <AdornedElementPlaceholder Name="MyAdorner" ></AdornedElementPlaceholder>
            </Border>
            <TextBlock
                  Margin="5,0,0,0"
                  Foreground="Red" 
                  Text="{Binding [0].ErrorContent}">
           </TextBlock>
         </StackPanel>
       </ControlTemplate>
   </Setter.Value>
 </Setter>

于 2013-09-18T19:42:22.203 回答