Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple styles to one control?

Tags:

wpf

xaml

I'm trying to set multiple styles in a button, in particular I've:

style (1) => Style="{StaticResource VisibleAnimation}"
style (2) => Style="{DynamicResource AccentedSquareButtonStyle}"

A pseudo code:

<Button Content="Invia" Style="{DynamicResource AccentedSquareButtonStyle, VisibleAnimation}" ></Button>

EDIT: POSSIBLE SOLUTION WITH MERGE

<Style TargetType="FrameworkElement" x:Key="VisibleAnimation" BasedOn="{DynamicResource AccentedSquareButtonStyle}">

The compiler underlined the BasedOn line and display me:

Unable to set the properties for DynamicResourceExtension basedon type style. You can set DynamicResourceExtension only for a Dependency Property of a DependencyObject.

How I can achieve this?

like image 859
Bender Avatar asked Sep 12 '15 08:09

Bender


2 Answers

You could make Style1 basedon Style2 or vise versa, then apply the top level style to your button,

<Window.Resources>
<Style TargetType="Button" x:Key="Style1">
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
<Style TargetType="Button" x:Key="Style2" BasedOn="{StaticResource Style1}">
    <Setter Property="Background" Value="Green"/>
</Style>


but if you don't wan't to change any if your two styles (they are used elsewhere for example) follow this blog post to extend your button style.

like image 185
SamTh3D3v Avatar answered Oct 18 '22 23:10

SamTh3D3v


You can only set one Style to the control. However you can "merge" styles by using Style.BasedOn property. Example:

<Style TargetType="Button" x:Key="style1">
    <Setter Property="Background" Value="Red"/>
    <!-- some other setters here -->
</Style>

<Style TargetType="Button" BasedOn="{StaticResource style1}">
    <Setter Property="BorderBrush" Value="Green"/>
    <Setter Property="BorderThickness" Value="2"/>
    <!-- some othe setters maybe-->
</Style>

The second style "merges" his setters and setters from style that he derives from. So applying the second style sets the Button Background to Red and BorderBrush to Green. The second style has no x:Key property. This means it would be applied for every Button automatically. You can define only one such style in one ResourceDictionary

like image 20
bakala12 Avatar answered Oct 18 '22 23:10

bakala12