5

我对多个字段之间的验证有疑问。例如,我有一个名为 ViewModel 的视图模型RangeDateViewModel,其中包含一个名为的类的 2 个实例DateViewModel——它们分别代表开始日期和结束日期。

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

<TextBox Text="{Binding StartDate.Date, ValidateOnDataError=True}">
<TextBox Text="{Binding EndDate.Date, ValidateOnDataError=True}">

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

public string this[string columnName]
{
     get
     {
        return ValidationError();
     }
}

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

我猜这是因为绑定属性不在同一级别RangeDateViewModel,而是在 child 内部DateViewModel

我认为我的需求是非常基本的,必须有一个简单的解决方案来解决这个问题。

我尝试使用 ValidationRules 而不是,IDataErrorInfo但后来我无法让 ViewModel 从 ValidationRules 知道当前的验证状态。

4

2 回答 2

1

尝试使用以下方法:

  1. 创建一个DataTemplateDateViewModel

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

    <ContentControl Content="{Binding StartDate, ValidateOnDataError=True}" />
    <ContentControl Content="{Binding EndDate, ValidateOnDataError=True}" />
    
  3. RangeDateViewModel订阅PropertyChanged事件StartDate并且在引发时,使用/EndDate引发PropertyChanged事件:StartDateEndDate

    StartDate.PropertyChanged += (s, e) => InvokePropertyChanged("StartDate");
    EndDate.PropertyChanged += (s, e) => InvokePropertyChanged("EndDate");
    
于 2011-12-06T09:54:11.277 回答
1

我遇到了public string this[string columnName]前一周根本没有提到的问题。

解决方案很简单。绑定 WPF 绑定引擎无法遵循我的 ViewModel 的嵌套。

我曾假设我需要在 ViewModel 中实现作为当前 DataContext 的属性,但需要在绑定到控件的 ViewModel 中实现。

例子:

<TextBox Text="{Binding Path=ProductViewModel.DescriptionViewModel.ProductName,
                                    Mode=TwoWay,
                                    ValidatesOnDataErrors=True,
                                    NotifyOnValidationError=True}" />

DescriptionViewModel是包含绑定属性的类。IDataErrorInfo需要在该类中实现(而不是ProductViewModel可能包含它的层次结构中或另一个类中),那么一切都会正常工作。

于 2011-12-06T12:24:45.013 回答