I want to create a style which I can apply to different control types. Something like this:
<ToolBar>
<ToolBar.Resources>
<Style TargetType="Control">
<Setter Property="Margin" Value="1"/>
<Setter Property="Padding" Value="0"/>
</Style>
</ToolBar.Resources>
<ComboBox .../>
<Button .../>
</ToolBar>
And it should apply to the ComboBox
and the Button
. But it doesn't work like I've written it here.
Is this possible somehow? To target only an ancestor of these classes, like Control
? If not, what would be the best way to apply common settings to a bunch of control?开发者_开发知识库
Update
See this discussion for an interesting approach
See this question
The Style you are creating is only targeting Control and not elements that derive from Control. When you don't set the x:Key you implicitly set the x:Key to TargetType, so if TargetType="Control", then x:Key="Control". I don't think there's any direct way to accomplish this.
Your options are
<Style x:Key="ControlBaseStyle" TargetType="Control">
<Setter Property="Margin" Value="1"/>
<Setter Property="Padding" Value="0"/>
</Style>
Target all Buttons and ComboBoxes for instance
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource ControlBaseStyle}"/>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ControlBaseStyle}"/>
or use the the style directly on the Control
<Button Style="{StaticResource ControlBaseStyle}" ...>
<ComboBox Style="{StaticResource ControlBaseStyle}" ...>
I do not believe that styles support inheritance in the conventional programming form. It seems like your best bet would be to do what Meleak is suggesting in his first example. This would force each control type to have the same base style, but still allow you the option to extend the styles for each type if you need too.
精彩评论