将样式的TargetType属性设置为基类

我只是在WPF中探索一下,并希望我的窗口上的所有元素共享相同的边距。 我发现所有能够有余量的控件都是从FrameworkElement派生的,所以我尝试了以下方法:

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

而且,这不起作用。 我可以将其应用于所有button,但不适用于从Button派生的所有元素。 我错过了什么,或者这是不可能的?

我唯一一个喜欢使用CSS的WPF会是一个好主意?

不幸的是,你不能将样式应用到基本的FrameworkElementtypes; 而WPF会让你编写风格,它不会将其应用于从它派生的控件。 看来,这也适用于FrameworkElement的子types,例如ButtonBase,Button / ToggleButton / RepeatButton的超types。

您仍然可以使用inheritance,但必须使用明确的BasedOn语法将其应用于您希望应用的控件types。

 <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> 

问题是,当search一个样式WPF不会search当前的派生所有类。 但是,您可以将样式设置为一个键,并将其应用于您希望具有共同属性的所有元素。 如果在样式中指定的属性不能应用到正在设置样式的元素,则会忽略该属性。