當Validation.HasError
爲true時,可以將默認邊框設置爲綠色,並在觸發器中將其更改。
使用msdn exapmle,就可以在風格設定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);
}
}
}
來源
2017-02-22 02:17:40
Ron
是有辦法我可以避免綠色作爲默認? ,因爲我想在普通文本框爲空時 – mark
向樣式添加另一個觸發器以考慮更多的案例。看我的編輯。 – Ron
請注意,在這個例子中,你應該使用Age屬性的Nullable int(int?)。 – Ron