在不同级别的多个字段之间进行验证

Dro*_*ror 5 validation wpf mvvm idataerrorinfo validationrules

我遇到了多个字段之间的验证问题.例如 - 我得到了一个名为RangeDateViewModel的ViewModel,它包含名为DateViewModel的类的2个实例,每个实例分别代表一个开始日期和结束日期.

所以我的绑定看起来像这样 -

<TextBox Text="{Binding StartDate.Date, ValidateOnDataError=True}">
<TextBox Text="{Binding EndDate.Date, ValidateOnDataError=True}">
Run Code Online (Sandbox Code Playgroud)

我的RangeDateViewModel类实现了IDataErrorInfo接口.在我的计划中,RangeDateViewModel将通过在IDataErrorInfo ["propertyName"]函数中应用验证逻辑来​​验证开始日期是否在结束日期之前 -

    public string this[string columnName]
    {
         get
         {
            return ValidationError();
         }
     }
Run Code Online (Sandbox Code Playgroud)

问题是永远不会调用它,而是调用驻留在每个DateViewModel类中的IDataErrorInfo属性.

我想这是因为bound属性不在RangeDateViewModel的同一级别,而是在子DateViewModel中.

我认为我的需求是非常基本的,必须有一个简单的解决方案来解决这个问题.我尝试使用ValidationRules而不是IDataErrorInfo,但后来我遇到了问题,让ViewModel知道ValidationRules当前的验证状态.

Dan*_*rth 1

尝试使用以下方法:

  1. 创建DataTemplate一个DateViewModel

    <DataTemplate DataType="{x:Type ViewModels:DateViewModel}">
        <TextBox Text="{Binding Date}">
    </DataTemplate>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将此 ViewModel 的实例绑定到 ContentControl 并设置ValidateOnDataError为该true绑定:

    <ContentControl Content="{Binding StartDate, ValidateOnDataError=True}" />
    <ContentControl Content="{Binding EndDate, ValidateOnDataError=True}" />
    
    Run Code Online (Sandbox Code Playgroud)
  3. RangeDateViewModel订阅和PropertyChanged事件时,当引发时,使用/引发事件:StartDateEndDatePropertyChangedStartDateEndDate

    StartDate.PropertyChanged += (s, e) => InvokePropertyChanged("StartDate");
    EndDate.PropertyChanged += (s, e) => InvokePropertyChanged("EndDate");
    
    Run Code Online (Sandbox Code Playgroud)