Aaron Reynolds

… the ramblings of a fool

WPF: Custom Expander (to fix Header alignment)

This post describes how to create a custom Expander control to fix issues with the alignment of content in the Header element of the Expander control.

Edit: it is also possible to do something similar using the method is this post by Patrick Jones/John Smith however my method gives you the option to customise the header with additional controls and use the modified design as a custom control.

While creating a WPF project I wanted to put icons into the header of an expander.

Now you can do this anyway but the ContentPresenter within the Header template has an inherent HorizontalAlignment property of “Left” so you end up with all the content left-aligned.

See this post for a summary of the issue: Expander with Custom Header.

After a fair bit of Googling and plenty of pointers without a solid answer I put together a custom control with this fix embedded. The steps I took are below.

1. Create a WPF Custom Control Library in Visual Studio and create a Custom Control (WPF) named e.g. “ExpanderPlus.cs”.

2. In the code-behind file, change the base class from “Control” to “Expander”.

3. You’ll notice a “Generic.xaml” theme file is created for you in the “Themes” sub-folder of the project.

4. Open up the “Expander” type in StyleSnooper or Reflector and BAML Viewer. Or you can obtain the XAML from here: WPF Document Samples.

5. Copy the XAML into your Generic.xaml file. Copy the entire <style> tag in place of the <style> tag. Then change the “TargetType” attribute to match the name of your custom control e.g. TargetType=”{x:Type local:ExpanderPlus}” in my case.

6. Implement the fix: search for “ContentPresenter” and then scroll across within the tag until you find the “HorizontalAlignment” attribute/property and change it to be HorizontalAlignment=”{TemplateBinding Control.HorizontalContentAlignment}”.

You now have a custom expander control which allows you to use the full width of the Header element for your content.

You then just reference the CCL in your WPF Application project and include it in your user control or window.

I’ve uploaded 2 images that show how I’ve customised this implementation for my use. You could further custom the custom Expander header but this was meant as a simple example for you to follow.

Custom Expander in Use: XAML and Design:

WPF custom expander control XAML

WPF custom expander control XAML

WPF custom expander control Design

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *