Long after this post was written, a fellow by the name of Patrick Jones left a comment which showed another way to implement the functionality shown in this post. Upon reading his clever implementation, I realized that this is entirely possible to achieve without writing a single line of code. The trick relies on binding the Expander’s header element’s Width to the ActualWidth of the Expander. Here’s a demo:
Text=”I am header text…”
I am some content…
Note: This technique makes the header element wider than the available space (it does not subtract out the width of the Expander’s expansion indicator). If your header element has a border around it, such as a Button, this XAML-only technique will not work properly because the header element is clipped on the righthand side. If you need the header element to be exactly the right width, then you will need to use the approach explained below.
Someone recently asked me how to stretch the content of an Expander’s header. By default the Expander will force the header’s content to “auto-size” itself, like this:
In the screenshot above, a DataTemplate was applied to the Expander’s HeaderTemplate property. That template consists of a Border with a blue background wrapping a ContentPresenter. Notice that the Border does not extend all the way to the right edge of the header area. The desired effect is to have the header content stretch, like this:
I first tried to make the header content stretch by setting properties on the Border in the DataTemplate. No matter which properties I set it had no effect, so I realized that a little Snooping was necessary to get to the bottom of this. I fired up Snoop and soon realized why I could not stretch the header content. The ContentPresenter which hosts the expanded HeaderTemplate elements (note, ‘expanded’ in the sense of ‘instantiated’) has its HorizontalAlignment explicitly set to ‘Left’. D’oh!
Here’s what I’m referring to, when using the Expander’s default HeaderTemplate:
The question now is: how can we set that ContentPresenter’s HorizontalAlignment to ‘Stretch’?
I know of two good ways to go about setting that property. We could get a copy of Expander’s default control template (for each OS theme…), find the ContentPresenter in the template, set the HorizontalAlignment to ‘Stretch’, and then use that modified control template in our application. For you XAML-only zealots out there, that’s the way to go.
You can download the demo project here. Change the file extension from .DOC to .ZIP and then decompress it.