Wpf TargetType在生成的控件上不起作用?

Wpf TargetType在生成的控件上不起作用?,wpf,styles,Wpf,Styles,我试图实现的是在运行时自动设置按钮的样式。因此,我希望不使用以下选项: dirButton.Style = (Style)Application.Current.FindResource("DirectoryStyle"); 这是我在App.xaml中定义的样式(出于显示目的,我删除了setter): 简言之: 有没有办法使TargetType影响生成的控件?从样式声明中删除x:Key,使其成为TargetType的默认样式 <Style TargetType="{x:Type loca

我试图实现的是在运行时自动设置按钮的样式。因此,我希望不使用以下选项:

dirButton.Style = (Style)Application.Current.FindResource("DirectoryStyle");
这是我在App.xaml中定义的样式(出于显示目的,我删除了setter):

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

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

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

...

谢谢,这正是我的意思!
Directory Button dirButton = new DirectoryButton();

dirButton.Click += directoryButton_Click;
// Here I could set the style with the first code segment
<Style TargetType="{x:Type local:DirectoryButton}">
    ...
</Style>