Reputation: 53
I have a Textbox that bind to a validation rule. I am able to display red border when Validation.HasError is True
However, I am not able to display green border when user input is correct and I found that because my Trigger property replys on Validation.HasError and Validation.HasError IS NOT False when there is no validation error.
I wonder if there is a proper way or workaround to achieve this?
Upvotes: 0
Views: 874
Reputation: 3631
You can set the default Border to be Green, change it in Trigger, when Validation.HasError
is true.
Using msdn exapmle, you can set BorderBrush
and BorderThickness
in the Style:
<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>
Other parts of the code are
<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>
and
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);
}
}
}
Upvotes: 3