我试图在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>
发生验证错误时,来自ValidationResult
类的posintValidationRule
文本出现在工具提示中(“值必须是整数”等)。
如何在Validation.ErrorTemplate
的TextBlock中显示相同的文本,现在,如果出现错误,只说:“有错误”?
答案 0 :(得分:4)
我找到了解决方案:
<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>
一切正常
答案 1 :(得分: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>