Search code examples
wpfvb.netxamlexpander

Wpf change the background colour of an expander's header only


I have looked at many questions/answers but couldn't find what I was exactly looking for,

I am trying to change the background colour of the expander's header only and not have the same colour continue for the content within the expander. Preferably within xaml but a vb.net solution would suffice.

(Any comments or suggestions will be helpful)

If this is a duplicated question please direct me to the answer and leave the question open to help others avoid the same issue in the future!

Thanks.


Solution

  • I am not sure whether this is what you are exactly looking for, but you could change the header background by simply doing that:

     <Expander VerticalAlignment="Center">
            <Expander.Header>
                <Grid Background="LightBlue">
                    <TextBlock Text="Expander Header"/>
                </Grid>
            </Expander.Header>
            <StackPanel>
                <TextBlock Text="Cotent"></TextBlock>
            </StackPanel>
        </Expander>
    

    enter image description here

    Or you could override the default Expander's Header DataTemplate by using HeaderTemplate

    <Window.Resources>
        <DataTemplate x:Key="HeaderText">
            <Border Height="25" Background="LightBlue">
                <TextBlock Text="{Binding}" 
                        Margin="4 0"
                        VerticalAlignment="Center"
                        Foreground="White"
                        FontSize="11" 
                        FontWeight="Normal"
                       />
            </Border>
        </DataTemplate>
    
        <Style TargetType="{x:Type Expander}">
            <Setter Property="HeaderTemplate" Value="{StaticResource HeaderText}"/>
        </Style>
    </Window.Resources>
    
    
    <Grid x:Name="LayoutRoot">
        <Expander VerticalAlignment="Center" Header="Expander Header">        
            <StackPanel>
                <TextBlock Text="Cotent"></TextBlock>
            </StackPanel>
        </Expander>
    </Grid>