Tig*_*ine 43 wpf styles targettype
我只是在WPF中挖了一下,并希望我窗口上的所有元素共享相同的边距.我发现所有能够具有边距的控件都派生自FrameworkElement,所以我尝试了以下方法:
<Window.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="10" />
</Style>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
而且,这不起作用.我可以将它应用于所有按钮,但不能应用于从Button派生的所有元素.我错过了什么或者这根本不可能吗?
我是唯一一个觉得使用CSS for WPF的人会是个好主意吗?
Nic*_*ong 59
不幸的是,您无法将样式应用于基础FrameworkElement类型; 虽然WPF将允许您编写样式,但它不会将其应用于从中派生的控件.看起来这也适用于FrameworkElement的子类型,例如ButtonBase,Button/ToggleButton/RepeatButton的超类型.
您仍然可以使用继承,但您必须使用显式BasedOn语法将其应用于您希望它应用于的控件类型.
<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>
Run Code Online (Sandbox Code Playgroud)
问题是,在搜索样式时,WPF不会搜索当前派生的所有类.但是,您可以为该样式指定一个键,并将其应用于您希望拥有共同属性的所有元素.如果在样式中指定了无法应用于样式元素的属性,则会忽略该属性.