Setting a style's TargetType property to a base class

自闭症网瘾萝莉.ら 提交于 2019-11-27 04:44:16
Nicholas Armstrong

Unfortunately, you cannot apply styles to the base FrameworkElement type; while WPF will let you write the style, it will not apply it to the controls that derive from it. It appears that this also applies to subtypes of FrameworkElement, e.g. ButtonBase, the supertype of Button/ToggleButton/RepeatButton.

You can still use inheritance, but you will have to use the explicit BasedOn syntax to apply it to the control types you want it to apply to.

<Window.Resources>
    <Style TargetType="{x:Type FrameworkElement}">
        <Setter Property="Margin" Value="10" />
    </Style>

    <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />

</Window.Resources>

The issue is that when searching for a style WPF does not search through all classes from which the current one derives. However you can give the style a key and apply it to all elements for which you wish to have a common property. If a property is specified in the style that cannot be applied to the element you are styling, it is ignored.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!