我可以在WPF中使用一个具有多个TargetType的样式吗?

Kin*_*han 30 c# silverlight wpf targettype

标题为,我的意思如下:

<Style TargetType="{x:Type TextBlock}" 
       TargetType="{x:Type Label}"  
       TargetType="{x:Type Button}" >
Run Code Online (Sandbox Code Playgroud)

这实际上是为了使用第三方控件,我继承了他们的类.但是模板不适用于SubClass,因为TargetType它位于基类上.所以我想设置多个TargetTypes以使它能够同时申请.

Rac*_*hel 51

不,你不能,但我经常为共享基类创建一个样式FrameworkElement,然后创建我BasedOn的基本样式的单独控件样式

<Style TargetType="{x:Type FrameworkElement}">
    <!-- Shared Setters -->
</Style>

<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,有许多属性“FrameworkElement”不包含(例如与字体相关的属性),因此它们无法包含在样式设置器中。您可以选择“ContentControl”,但这不适用于此特定示例,因为“TextBlock”不继承自“ContentControl”。 (4认同)

alt*_*fox 8

Rachel的答案更灵活的变化是使用resourceKey for BasedOn.

所以,而不是:

<Style TargetType="{x:Type FrameworkElement}">
    <!-- Shared Setters -->
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
Run Code Online (Sandbox Code Playgroud)


做类似的事情:

<Style x:Key="commonStyle" TargetType="{x:Type FrameworkElement}">
    <!-- Shared Setters -->
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource commonStyle}" />
Run Code Online (Sandbox Code Playgroud)


这提供了更多选项,因为一些样式可以基于commonStyle,一些样式可以基于例如commonStyle2,其中commonStyle和commonStyle2都将FrameworkElement作为目标类型.