Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf create style for named element

Tags:

c#

wpf

xaml

Is it possible to add style to xaml element without editing the element?

for example:

xaml element:

<Grid>
     <Grid x:Name="A">content A</Grid>
     <Grid x:Name="B">content B</Grid>
</Grid>

and style:

<Style x:Key="StyleForA" TargetName="A" TargetType="{x:Type Grid}" >
   <Setter Property="Background" Value="Red"/>
</Style>
<Style x:Key="StyleForB" TargetName="B" TargetType="{x:Type Grid}" >
   <Setter Property="Background" Value="Green"/>
</Style>

UPD: I have a project with a lot of styles (aero, black, etc ).

And if I edit the element Style="{StaticResources StyleForA}" I must edit all styles. So I need to create local style that affected to named element.

like image 377
Dr_klo Avatar asked Oct 31 '22 08:10

Dr_klo


1 Answers

Natively you can't.

But without touching your XAML, you can do it very easily using code :

    Grd1.Style = (Style) this.Resources["GridKey"];

Pure XAML approach using Blend behaviors,

<Grid x:Name="Grd1">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <ic:ChangePropertyAction PropertyName="Style" Value="{DynamicResource GridKey}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Grid>
like image 171
AnjumSKhan Avatar answered Nov 15 '22 06:11

AnjumSKhan