Search code examples
wpfxamltogglebuttontemplatingexpander

WPF ContentPresenter overrides othe Controls on the same level


As in my last question I'm about to re-create an expander + it's toggle button.

Expander Template:

<ControlTemplate TargetType="Expander">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="15"/>
        </Grid.RowDefinitions>
        <ContentPresenter x:Name="ContentPresenter" Grid.Row="0"/>
        <ToggleButton Grid.Row="1" >
           ....
        </ToggleButton>
    </Grid>

Now when I use this Custom Control in my Main View and add a Control (e.g. a Button):

<custom:FullWidthExpander Width="200" HeaderBackground="Gray">
    <Button />
</custom:FullWidthExpander>

The ToggleButton (which is defined in my Expander Template above) gets overridden by this Button.


Solution

  • Are you binding the UserControl.Content to the Expander.Content property?

    <!-- define a custom Template for the UserControl FullWidthExpander -->
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <!-- be sure to include the Content binding to pass the UC.Content to Expander -->
            <Expander Content="{TemplateBinding Content}">
                <!-- create a custom Template for this Expander -->
                <Expander.Template>
                    <ControlTemplate TargetType="Expander">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition x:Name="ContentRow" Height="*"/>
                                <RowDefinition Height="20"/>
                            </Grid.RowDefinitions>
                            <ContentPresenter Grid.Row="0" Content="{TemplateBinding Content}"/>
                            <ToggleButton Grid.Row="1" Content="Test Toggle Button" />
                        </Grid>
                    </ControlTemplate>
                </Expander.Template>
            </Expander>
        </ControlTemplate>
    </UserControl.Template>
    

    I did a quick test, and this works fine when using the control like this :

    <local:FullWidthExpander>
        <Button Content="Test Content Button"/>
    </local:FullWidthExpander>
    

    enter image description here

    I also took a look at your other question, and if you have your ControlTemplate.Triggers here then you will also want to make sure to set Expander.IsExpanded to True in order to view your Content. Your trigger is hiding the top content row if IsExpanded=False, which is the default for an Expander.