Search code examples
wpfwpf-style

WPF - combine/link multiple styles into one


In my WPF application I want to style a data grid. For this I need several separate styles (sub styles), since they target different controls. Now I want to combine those into one style (main style) to set it in xml via <DataGrid Style="{StaticResource MyDataGridStyle}">

Pseudo code for sub styles:

<ResourceDictionary>
    <!-- sub styles -->
    <Style x:Key="RowStyle" TargetType="Row">...</Style>
    <Style x:Key="ColumnStyle" TargetType="Column">...</Style>
    <Style x:Key="ColumnHeaderStyle" TargetType="ColumnHeader">...</Style>
    <Style x:Key="SomeInnerElementStyle" TargetType="SomeInnerElement">...</Style>
</ResourceDictionary>

Currently I'm combining the styles via

<!-- inside the ResourceDictionary -->
<!-- main style -->
<Style x:Key="MyDataGridStyle" TargetType="DataGrid">
    <Style.Resources>
        <Style BasedOn="{StaticResource RowStyle}" TargetType="Row" />
        ... all other sub styles go here
    </Style.Resources>
</Style>

Is there a more elegant way of including the sub styles in my main style? The BasedOn attribute forces me to specify the TargetType again, which is a pain and also I do not want to include "a new style based on the sub style" but just "the sub style".


Solution

  • Set the corresponding Style properties:

    <Style x:Key="MyDataGridStyle" TargetType="DataGrid">
        <Setter Property="RowStyle" Value="{StaticResource RowStyle}" />
        <Setter Property="ColumnStyle" Value="{StaticResource ColumnStyle}" />
        <Setter Property="ColumnHeaderStyle" Value="{StaticResource ColumnHeaderStyle}" />
    </Style>