検証ルールにバインドする Textbox があります。Validation.HasError が True の場合、赤い境界線を表示できます
ただし、ユーザー入力が正しい場合は緑色の境界線を表示できません。検証エラーがない場合、Trigger プロパティがValidation.HasErrorおよびValidation.HasError IS NOT False で応答するためです。
これを達成するための適切な方法または回避策があるのだろうか?
検証ルールにバインドする Textbox があります。Validation.HasError が True の場合、赤い境界線を表示できます
ただし、ユーザー入力が正しい場合は緑色の境界線を表示できません。検証エラーがない場合、Trigger プロパティがValidation.HasErrorおよびValidation.HasError IS NOT False で応答するためです。
これを達成するための適切な方法または回避策があるのだろうか?
Validation.HasError
が true の場合、デフォルトの Border を Green に設定し、Trigger で変更できます。
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);
}
}
}