0
votes

I have an Expander style which applied template on both Header and Content

I wish to have one of the TextBlock inside content's template to match the Header's TextBlock's Foreground color

<Style TargetType="Expander">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Foreground="Blue"/> <!--Header TextBlock-->
            </DataTemplate>
        </Setter.Value>
     </Setter>
     <Setter Property="ContentTemplate">
          <Setter.Value>
              <DataTemplate>
                  <ItemsControl>
                      <ItemsControl.ItemTemplate>
                          <DataTemplate>
                              <TextBlock/> <!--Match Header TextBlock's Foreground-->
                          </DataTemplate>
                      </ItemsControl.ItemTemplate>
                  </ItemsControl>
              </DataTemplate>
          </Setter.Value>
     </Setter>
</Style>

I have tried ElemenName binding but it seems like the name scope is different since I am 2 template level deep.

I thought about TemplateBinding but I only want one of the column in the content to match the color of header instead of the whole expander.

I could apply the same trigger for the Header TextBlock on the Content TextBlock too but I am trying to see if there is a way to avoid duplicating the code.

1

1 Answers

0
votes

ElementName can't work across templates; with a template, you could have multiple elements with the same name.

Anything with different template instances reaching out to grope each other via the visual tree is going to be fraught with nameless horrors, whatever you do.

Instead, I would suggest that they both get their brushes from the same source. This is much more in line with how WPF is happy doing things.

  1. If the color won't change, use an appropriately-named Brush resource for both.

  2. If it will change, bind both to a viewmodel Brush property (kinda squicky, but not the end of the world), or use triggers driven by some other viewmodel property which represents the state being indicated by the color. The triggers would reference any number of appropriately-named Brush resources: ErrorBrush, HappyBrush, SadBrush, etc. By "name" I mean x:Key of course:

    <SolidColorBrush x:Key="HappyBrush">GreenYellow</SolidColorBrush>
    

    ...etc.