0
\$\begingroup\$

The following XAML is a close (tidied up) version of what I have use in my WPF application. If you have noticed there are two Styles applied to the same component (Border in this example.)

I would like to know how can I merge the 2nd Style into 1st to make it apply to all the Borders included in the DataTemplate.

<DataTemplate DataType="{x:Type m:myFoo}">
  <DataTemplate.Resources>
    <!-- 1) Style Applied to the Border -->
    <Style TargetType="Border">
      <Setter Property="Margin" Value="1"/>
    </Style>
  </DataTemplate.Resources>
  <Border>
    <Grid>
      <Border>
        <!-- Guts -->
      <Border>
    </Grid>
    <Border.Style>
      <!-- 2) Style Applied to the Border -->
      <Style TargetType="Border">
        <Style.Triggers>
          <DataTrigger Binding="{Binding Path=Active}">
            <Setter Property="Background" Value="OrangeRed"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </Border.Style>
  </Border>
</DataTemplate>

I am familiar with the fact that 2nd Style will only apply to its own component unlike the 1st which will be applied to any Border included in the DataTemplate.

\$\endgroup\$
1
\$\begingroup\$

You can merge the two style in the DataTemplate.Resources so that it can be applied in all the Borders inside the DataTemplate. Refer the below code.

<DataTemplate DataType="{x:Type m:myFoo}">
        <DataTemplate.Resources>
            <!-- 1) Style Applied to the Border -->
            <Style TargetType="Border">
                <Setter Property="Margin" Value="1"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Active}">
                        <Setter Property="Background" Value="OrangeRed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataTemplate.Resources>
        <Border>
            <Grid>
                <Border>
                    <!-- Guts -->
                 </Border>
            </Grid>                
        </Border>
    </DataTemplate>
\$\endgroup\$
2
  • \$\begingroup\$ I think he did this by design, so he can have other Borders without these properties. \$\endgroup\$
    – user34073
    Feb 22 '15 at 22:01
  • \$\begingroup\$ I am surprised I have missed the most obvious. I donno why on earth I didn't think of this on the time of writing the snippet. This is literally the 2nd trigger untouched and moved to the 1st spot as it was. I must have given it a go with a typo or something and thought I donno how to do this. Thanks. \$\endgroup\$
    – Mehrad
    Feb 22 '15 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.