使用组合从XAML错误模板访问INotifyDataErrorInfo验证错误



我的视图模型基类最初实现了INotifyDataErrorInfo,一切工作都完美无缺,但我现在正在探索如何使用组合而不是继承来进行验证,这样我的基本视图模型类就不必做任何事情,而只需要做INotifyPropertyChanged。我也在寻找一个可重用的解决方案,所以我不必在我所有的视图模型上实现INotifyDataErrorInfo。

我创建了INotifyDataErrorInfo的具体实现,我可以将其包含在需要验证的视图模型中(仅包含相关代码):

public class NotifyDataErrorInfo : INotifyDataErrorInfo
{
public readonly Dictionary<string, string> ValidationErrorsByPropertyName = new Dictionary<string, string>();
public IEnumerable GetErrors(string propertyName)
{
...
}
public bool HasErrors { get; }
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
}

当MyViewModel有验证错误时,它通过NotifyDataErrorInfo对象的实例获取/设置它们。(在我的原始版本中,ViewModel实现了INotifyDataErrorInfo。当我尝试通过组合达到同样的效果时,情况就不再是这样了。

public class MyViewModel : ViewModel
{
public NotifyDataErrorInfo NotifyDataErrorInfo { get; } = new NotifyDataErrorInfo();
}

这是一个文本框,报告MaxDaysText属性setter上的验证错误,并设置验证错误模板。

<TextBox        
Text="{Binding MaxDaysText, UpdateSourceTrigger=PropertyChanged}"
Validation.ErrorTemplate="{StaticResource TextBoxValidationErrorTemplate}" />

我现在需要更新我的验证错误模板,以访问NotifyDataErrorInfo属性中的错误,但我不确定如何做到这一点。

<ControlTemplate x:Key="TextBoxValidationErrorTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
HorizontalAlignment="Left"
BorderBrush="{StaticResource ErrorMessageBorderBrush}"
BorderThickness="1">
<AdornedElementPlaceholder x:Name="_adornedElementPlaceholder" />
</Border>
<ItemsControl
Grid.Row="1"
ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox
Style="{StaticResource ErrorMessageStyle}"
Text="{Binding Path=ErrorContent, Mode=OneWay}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</ControlTemplate>

我试过改变所有的绑定来寻找NotifyDataErrorInfo,但没有运气。我需要对模板做什么更改来访问MyViewModel的NotifyDataErrorInfo属性上的验证错误?

编辑:在复合方法中,ErrorsChanged总是为空,并且视图永远不会被通知。我猜当视图模型本身实现INotifyDataErrorInfo时,框架使用ErrorsChangedEventManager分配委托。但现在我把它排除在循环之外。因此,复合似乎不适用于这种方法。这种评估正确吗?

属性名为' NotifyDataErrorInfo ',您需要将ItemsSource绑定到该属性

<ItemsControl
Grid.Row="1"
ItemsSource="{Binding NotifyDataErrorInfo}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox
Style="{StaticResource ErrorMessageStyle}"
Text="{Binding Path=ErrorContent, Mode=OneWay}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

如果controltemplate没有检索数据上下文,那么您需要添加它

<ControlTemplate DataContext={Binding DataContext, 
RelativeSource={RelativeSource AncestorType={x:Type views:YourView}}} x:Key="TextBoxValidationErrorTemplate">

相关内容

最新更新