I want to have a custom header in the Expander control. I want to have a header text with left alignment and a picture with a right alignment:
<Expander>
<Expander.Header>
<DockPanel LastChildFill="True" HorizontalAlignment="Stretch">
<TextBlock DockPanel.Dock="Left" Text="Some Header Text"/>
<Image DockPanel.Dock="Right" HorizontalAlignment="Right" />
</DockPanel>
</Expander.Header>
<StackPanel >
<ItemsPresenter />
</StackPanel>
</Expander>
Unfortunately the header is rendered inside of an element which doesn't stretch horizontaly by default. That element is a ContentPresenter control, and it doesn't stretch by default because it's HorisontalAlign value is Left. If I change it to Stretch (I've done this in the Snoop tool), then the header is rendered as I want it. But how do I change it from code?
I've tried adding ContentPresenter style to Expander resources with correct HorizontalAlignment value, but unfortunately it doesn't work. Probably ContentPresenter has some custom style applied, and that's why it didn't grab my styling. I've tried it like this:
<Expander.Resources>
<Converters:TodoTypeToHeaderTextConverter x:Key="TodoTypeToHeaderTextConverter" />
<Style TargetType="ContentPresenter">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</Expander.Resources>
So what else can I try?
Try something like that:
XAML file:
<Expander Name="exp" Header="test" Loaded="exp_Loaded">
<Expander.HeaderTemplate>
<DataTemplate>
<DockPanel LastChildFill="True" HorizontalAlignment="Stretch">
<TextBlock DockPanel.Dock="Left" Text="{Binding}"/>
<Image Source="/ExpanderStyle;component/animation.png" Width="20"
DockPanel.Dock="Right" HorizontalAlignment="Right" />
</DockPanel>
</DataTemplate>
</Expander.HeaderTemplate>
</Expander>
Code-behind:
private void exp_Loaded(object sender, RoutedEventArgs e)
{
var tmp = VTHelper.FindChild<ContentPresenter>(sender as Expander);
if (tmp != null)
{
tmp.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
}
}
And helper class:
public static class VTHelper
{
public static T FindChild<T>(DependencyObject parent) where T : DependencyObject
{
if (parent == null) return null;
T childElement = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
childElement = FindChild<T>(child);
if (childElement != null)
break;
}
else
{
childElement = (T)child;
break;
}
}
return childElement;
}
}