You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:55:05