我有一个绑定到验证规则的文本框。当 Validation.HasError 为 True 时,我可以显示红色边框
但是,当用户输入正确时,我无法显示绿色边框,我发现这是因为我的 Trigger 属性在没有验证错误时回复Validation.HasError和Validation.HasError IS NOT False。
我想知道是否有适当的方法或解决方法来实现这一目标?
我有一个绑定到验证规则的文本框。当 Validation.HasError 为 True 时,我可以显示红色边框
但是,当用户输入正确时,我无法显示绿色边框,我发现这是因为我的 Trigger 属性在没有验证错误时回复Validation.HasError和Validation.HasError IS NOT False。
我想知道是否有适当的方法或解决方法来实现这一目标?
您可以将默认Border设置为Green,在Trigger中更改它,当Validation.HasError
为true时。
使用msdn exapmle,您可以在 Style中设置BorderBrush
和:BorderThickness
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Setter Property="BorderBrush" Value="Green"/>
<Setter Property="BorderThickness" Value="2"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="BorderBrush" Value="Red"/>
</Trigger>
<Trigger Property="TextBox.Text" Value="">
<Setter Property="BorderBrush" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
代码的其他部分是
<TextBox Name="textBox1" Width="50" Height="30" FontSize="15" DataContext="{Binding}"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}"
Grid.Row="1" Grid.Column="1" Margin="2">
<TextBox.Text>
<Binding Path="Age"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
和
public class AgeRangeRule : ValidationRule
{
private int _min;
private int _max;
public AgeRangeRule()
{
}
public int Min
{
get { return _min; }
set { _min = value; }
}
public int Max
{
get { return _max; }
set { _max = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;
try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if ((age < Min) || (age > Max))
{
return new ValidationResult(false,
"Please enter an age in the range: " + Min + " - " + Max + ".");
}
else
{
return new ValidationResult(true, null);
}
}
}