William Jockusch
William Jockusch

Reputation: 27295

Apply my own XAML style within a particular subtree

I have the following style. As done below, it works great:

    <StackPanel Orientation="Vertical">
      <StackPanel.Resources>
        <Style TargetType="TextBlock">
          <Setter Property="Padding" Value="0 0 0 0.3cm" />
          <Setter Property="Height" Value="Auto" />
          <Setter Property="VerticalAlignment" Value="Stretch" />
        </Style>
      </StackPanel.Resources>
      <TextBlock Text="Hello"/>
      <TextBlock Text="World"/>
    </StackPanel>

Now comes the problem. What I really want to do is define this style in a third place, then use it in various StackPanels, including their children, in the manner of the working sample above, but not in all StackPanels. This is what I've tried. It gives a build error:

<Window.Resources>
  <Style x:Key="TextBlockWithBottomMargin" TargetType="TextBlock">
    <Setter Property="Padding" Value="0 0 0 0.3cm" />
    <Setter Property="Height" Value="Auto" />
    <Setter Property="VerticalAlignment" Value="Stretch" />
  </Style>
</Window.Resources>
<Grid>
  <TabControl>
    <!-- omitting some XAML here -->
    <TabItem Header="Help" >
    <StackPanel Orientation="Vertical">
      <StackPanel.Resources>
        <Style Binding="{StaticResource TextBlockWithBottomMargin}"></Style> <!-- build error on this line -->
      </StackPanel.Resources>
      <TextBlock Text="Hello"/>
      <TextBlock Text="World"/>
    </StackPanel>
    <!-- lots more xaml here -->

Upvotes: 1

Views: 52

Answers (1)

Kylo Ren
Kylo Ren

Reputation: 8813

Use below code to create the style at a level:

<StackPanel.Resources>
     <Style TargetType="TextBlock" BasedOn="{StaticResource TextBlockWithBottomMargin}">
           <Setter .......      
     </Style>
</StackPanel.Resources>

Upvotes: 2

Related Questions