WPF自定义按钮Validation.ErrorTemplate失效问题排查与解决
问题原因与修复方案
问题原因
- 验证错误的关联对象是自定义控件
MyButtonWithValidation本身,而非模板内部的PART_Button。 - 你将
Validation.ErrorTemplate设置在了模板内的Button上,但该内部按钮仅通过TemplateBinding继承自定义控件的Command属性,并未直接绑定到ViewModel的SearchCommand,因此验证错误不会附加到它上面。 - 此时自定义控件本身未设置
Validation.ErrorTemplate,WPF会使用默认验证模板(仅显示红色边框),导致自定义错误消息无法显示。
修复方法
将Validation.ErrorTemplate作为Setter直接添加到自定义控件的Style中,而非嵌套在模板内部的Button上:
<Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type local:MyButtonWithValidation}"> <!-- 直接为自定义控件设置验证错误模板 --> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <StackPanel> <AdornedElementPlaceholder x:Name="adornedElement" /> <ItemsControl ItemsSource="{Binding}"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Foreground="Red" Text="{Binding ErrorContent}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:MyButtonWithValidation}"> <Grid> <Button x:Name="PART_Button" Command="{TemplateBinding Command}" Content="{TemplateBinding Content}"> </Button> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
原理说明
- 当ViewModel通过
INotifyDataErrorInfo报告SearchCommand的错误时,WPF会将错误附加到绑定目标元素(即MyButtonWithValidation)。 - 直接在Style中为自定义控件设置
Validation.ErrorTemplate,确保错误触发时使用你定义的模板渲染,而非WPF默认模板。
内容的提问来源于stack exchange,提问作者Dániel Erős
相关产品推荐
相关产品推荐

