下面是一个从绑定(bind)角度工作的模板,但错误模板不会显示,并且如果没有 AdornedElementPlaceholder,结果看起来有点花哨。
我的 View 模型实现了 IDataErrorInfo,通常我会通过将 ValidatesOnError=True 作为绑定(bind)的一部分来触发错误模板。此特定 View 模型仅用于显示,因此永远不会调用 IDataErrorInfo 索引器。不过,我确实有许多与验证相关的有用属性,包括 bool 值 IsValid 属性以及 IDataErrorInfo.Error,这两个属性都可以正确响应无效的 View 模型。
我应该将错误转换为 ValidationResult 并以这种方式触发它吗?或者有什么更简单的方法吗?
干杯,
贝里尔
当前模板
<!-- FooterViewModel DataTemplate -->
<DataTemplate DataType="{x:Type model:FooterViewModel}">
<Label x:Name="lblTotalTime"
Style="{StaticResource FooterStyle}"
Content="{Binding TotalTime, Converter={StaticResource TotalAmountConv}}" >
<Label.ToolTip>
<TextBlock Text="{Binding FeedbackMessage}" ></TextBlock>
</Label.ToolTip>
<Validation.ErrorTemplate>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right" Text=" *"
Foreground="Red"
FontWeight="Bold" FontSize="16"
/>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder Name="placeholder"></AdornedElementPlaceholder>
</Border>
</DockPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</Label>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsValid}" Value="False">
<Setter TargetName="lblTotalTime" Property="Control.BorderBrush" Value="Red"/>
<Setter TargetName="lblTotalTime" Property="Control.BorderThickness" Value="1"/>
<Setter TargetName="lblTotalTime" Property="Control.Background" Value="LightYellow"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
更新
好的,我只需更改绑定(bind)以包含 ValidatesOnErrors 即可启动 IDataErrorInfo,但错误模板仍然不显示。
这是绑定(bind)
<ItemsControl
ItemsSource="{Binding Path=FooterViewModels, Mode=OneWay, ValidatesOnDataErrors=True}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
最佳答案
默认情况下,仅在更新绑定(bind)的源时才运行验证。在您的 ItemsControl.ItemsSource 绑定(bind)中,源是您的 FooterViewsModels,显然它永远不会更新(因为您有 Mode=OneWay)。
您可以使用DataErrorValidationRule.ValidatesOnTargetUpdated当目标更新时也运行验证。该链接给出了一个示例。
请记住 Binding.ValidatesOnDataErrors属性只是将 DataErrorValidationRule 实例添加到 Binding.ValidationRules 集合的快捷方式。
最后,定义绑定(bind)的控件将具有 Validation.Errors 。在您的情况下,这是 ItemsControl,而不是其中的项目。因此,我相信您需要将 DataErrorValidationRule 添加到您的 Label.Content 绑定(bind)中。或者您需要在 ItemsControl 上定义 ErrorTemplate,具体取决于您的用途。
关于wpf - 如何触发此错误模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5249684/