TargetType 不适用于生成的控件?

TargetType does not work on generated Controls?

我试图实现的是设置一个在运行时自动生成的按钮的样式。所以我想不使用:

dirButton.Style = (Style)Application.Current.FindResource("DirectoryStyle");

这是我在 App.xaml 中定义的样式(出于显示目的我删除了设置器):

<Style x:Key="DirectoryStyle" TargetType="{x:Type local:DirectoryButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
 </Style>

上述按钮是在启动时生成的,代表给定目录中的一个文件夹。

Directory Button dirButton = new DirectoryButton();

dirButton.Click += directoryButton_Click;
// Here I could set the style with the first code segment

简而言之: 有没有办法让 TargetType 影响生成的控件?

从 Style 声明中删除 x:Key,使其成为 TargetType 的默认 Style。

<Style TargetType="{x:Type local:DirectoryButton}">
    ...
</Style>