Search code examples
c#wpfstylingdynamicresource

Apply same dynamic style to all elements of same kind in grid


I have a Grid full of Labels that all use the same style which is a DynamicResource:

<Label Grid.Row="0" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="1" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="2" Style="{DynamicResource MyStyle}"/>

Is there a way to only set the style once for all labels in the grid? I tried it this way, however BasedOn doesn't work with DynamicResources.


Solution

  • One way to do it is to use MergedDictionaries like so:

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/assemblyName;component/yourStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <!--If you want to include additional resources you need to place them here-->
            <SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
        </ResourceDictionary>
    </UserControl.Resources>
    

    Then in your Grid you can use it like so:

    <Grid>
        <Grid.Resources><!-- This will only use the style in the Grid-->
            <Style TargetType="Label" BasedOn="{StaticResource MyStyle}"/>
        </Grid.Resources>
    </Grid>  
    

    And this should now use your Style only for the Grid or a Label where Style="{StaticResource myStyle}".