WPF Expander.Header horizontal stretch

scher picture scher · Jul 1, 2015 · Viewed 11.2k times · Source

I have an Expander in Wpf. In the header I have Label on left aligned and want to have a button on the right site. I use the following XAML:

<Expander HorizontalAlignment="Stretch" IsExpanded="True">
    <Expander.Header >
        <Grid HorizontalAlignment="Stretch" Background="Aqua" Margin="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="Label on the left site"/>
            <Button Grid.Column="1" Content="Button on the right"/>
         </Grid>
    </Expander.Header>
    <Label Content="Some Content"/>
</Expander>

But that does not work. The button in the header is aligned to the left, next to the label. Can anyone explain me how to do it right?

Answer

Sinatr picture Sinatr · Jan 19, 2018

Expander header content presenter has horizontal alignment set to Left.

You can change it to Stretch using OneWayToSource binding of HorizontalAlignment (which is by default Stretch for Grid) like this:

<Expander>
    <Expander.Header>
        <Grid Background="Yellow">
            <TextBlock Text="Header"
                       HorizontalAlignment="{Binding HorizontalAlignment, RelativeSource={RelativeSource AncestorType=ContentPresenter}, Mode=OneWayToSource}" />
        </Grid>
    </Expander.Header>
</Expander>

P.S.: it took me more than it should to understand the solution of accepted answer, so I decide to save the time for future readers.