Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply a WPF style to different types at the same time?

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?

like image 705
Meh Avatar asked Dec 28 '22 05:12

Meh


1 Answers

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}" ...>
like image 153
Fredrik Hedblad Avatar answered Jan 13 '23 15:01

Fredrik Hedblad