6

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Meh
  • 7,016
  • 10
  • 53
  • 76

2 Answers2

12

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}" ...>
Community
  • 1
  • 1
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • I set both x:Key and x:Name on my style inside Generic.xaml but it does not show up when i type "StaticResource". I cannot bind it. All my other staticresources in Generic.xaml work. Is it not possible to make a staticresource of a style? – morknox Nov 03 '22 at 10:37
0

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.

Jason
  • 1,879
  • 16
  • 19