ksk*_*cou 2 c# validation wpf xaml inotifydataerrorinfo
我有一个TextBlock和一个CheckBox,例如:
<StackPanel >
<TextBlock Text="Colors"/>
<CheckBox Content="Blue" IsChecked="{Binding Model.Blue, ValidatesOnNotifyDataErrors=False}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
在我的模型中,我正在实现INotifyDataErrorInfo并验证是否选中了该复选框。如果未检查,则将其视为错误:
public class MyModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
[CustomValidation(typeof(MyModel), "CheckBoxRequired")]
public bool Blue
{
get { return _blue; }
set { _blue = value; RaisePropertyChanged(nameof(Blue)); }
}
public static ValidationResult CheckBoxRequired(object obj, ValidationContext context)
{
var model = (MyModel)context.ObjectInstance;
if (model.Blue == false)
return new ValidationResult("Blue required", new string[] { "Blue" });
else
return ValidationResult.Success;
}
//...
//INotifyPropertyChanged & INotifyDataErrorInfo implementations omitted
}
Run Code Online (Sandbox Code Playgroud)
当我已经ValidatesOnNotifyDataErrors设定true,它正确地显示周围的红色框CheckBox。看起来像这样:
我不希望出现红色复选框。为此,我明确设置ValidatesOnNotifyDataErrors为false。这很好。
出现错误时,我想做的是在上显示错误TextBlock,例如更改的字体颜色TextBlock。使用者如何TextBlock知道上出现的任何错误,CheckBox以及最佳的解决方法是什么?
我预期的结果将是这样的:
小智 5
首先设置ValidatesOnNotifyDataErrors不是消除红色边框的正确方法。这将导致您的数据完全无法验证。您想要的是:
<CheckBox Content="Blue" IsChecked="{Binding Model.Blue, ValidatesOnNotifyDataErrors=True}" Validation.ErrorTemplate="{x:Null}"/>
Run Code Online (Sandbox Code Playgroud)
其次,为了获得理想的结果,我将使用这种方法。您可以使用触发器来了解CheckBox中是否存在错误(该ErrorsChanged事件和HasError属性在此处应该很有用),并设置TextControl的文本颜色。
这是完成此操作的代码:
<TextBlock Text="Color">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=checkBox, Path=(Validation.HasError)}" Value="True">
<Setter Property="Foreground" Value="Red" />
<Setter Property="ToolTip" Value="{Binding ElementName=checkBox, Path=(Validation.Errors).CurrentItem.ErrorContent}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<CheckBox x:Name="checkBox"
Margin="4,0"
Content="Blue"
IsChecked="{Binding Model.Blue}"
Validation.ErrorTemplate="{x:Null}" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
985 次 |
| 最近记录: |