WPF show validation errors under custom button

I am creating a WPF application with the MVVM pattern.
Validation errors are managed by using INotifyDataErrorInfo. The ViewModel implements INotifyDataErrorInfo.

For System.Windows.Controls controls it works great, but it doesn’t work for custom controls.

In my application there is a custom button, like:

xaml:

<Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type local:MyButtonWithValidation}">
  <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>

C#:

using System.Windows;

namespace MyApp.Controls;

public class MyButtonWithValidation: System.Windows.Controls.Button
{
  static MyButtonWithValidation()
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButtonWithValidation), new FrameworkPropertyMetadata(typeof(MyButtonWithValidation)));
  }
}

If I use this button, it is visible and it executes the command bound to it and even the validation is working as expected (in case of validation error, the button is disabled and the validation message is written below the button in red):

<local:MyButtonWithValidation
    Command="{Binding SearchCommand}"
    Content="Search">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <AdornedElementPlaceholder x:Name="textBox" />
                <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock
                                Foreground="Red"
                                Text="{Binding ErrorContent}" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</local:MyButtonWithValidation>

Validation errors are managed by using INotifyDataErrorInfo. The ViewModel implements INotifyDataErrorInfo, like this:

private readonly Dictionary<string, List<string>> _errorsByPropertyName = new Dictionary<string, List<string>>();
public bool HasErrors => _errorsByPropertyName.Any();
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;

public IEnumerable GetErrors(string? propertyName)
{
    return propertyName is null || !_errorsByPropertyName.ContainsKey(propertyName)
         ? null
         : _errorsByPropertyName[propertyName];
}

In some cases I just apply a validation error, like:
AddError(nameof(SearchCommand), "Search validation error..."); // adds a new key-value pair ("SearchCommand", new List<string>() { "Search validation error..." }) to _errorsByPropertyName
As a result, there will be a validation error, and the error message is visible under the button.

Now, I want to move the Validation ErrorTemplate into MyButtonWithValidation:

<Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type local:MyButtonWithValidation}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:MyButtonWithValidation}">
        <Grid>
          <Button x:Name="PART_Button"
            Command="{TemplateBinding Command}"
            Content="{TemplateBinding Content}">
            <Validation.ErrorTemplate>
              <ControlTemplate>
                <StackPanel>
                  <AdornedElementPlaceholder x:Name="textBox" />
                  <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                      <DataTemplate>
                        <TextBlock
                          Foreground="Red"
                          Text="{Binding ErrorContent}" />
                      </DataTemplate>
                    </ItemsControl.ItemTemplate>
                  </ItemsControl>
                </StackPanel>
              </ControlTemplate>
            </Validation.ErrorTemplate>
          </Button>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

In this case, if I use MyButtonWithValidation like this, it doesn’t work as expected any more:

<local:MyButtonWithValidation
    Command="{Binding SearchCommand}"
    Content="Search">
</local:MyButtonWithValidation>

In this case a red border is created around the button and the error message is not visible. It is like the validation error would be “handled” by WPF and not the validation error template.

Why is this and how could it be fixed?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật