The Expander
control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?
Non stretchable Expander
s is usually the problem of non stretchable parent controls.. Perhaps one of the parent controls has defined a HorizontalAlignment
or VerticalAlignment
property?
If you can post some sample code, we can give you a better answer.
The accepted answer draws outside the control because the header content is in one column and the expander button is in the first. Might be good enough for some cases.
If you want a clean solution you have to change the template of the expander.
Another way is an attached property:
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
public static class ParentContentPresenter
{
public static readonly System.Windows.DependencyProperty HorizontalAlignmentProperty = System.Windows.DependencyProperty.RegisterAttached(
"HorizontalAlignment",
typeof(HorizontalAlignment),
typeof(ParentContentPresenter),
new PropertyMetadata(default(HorizontalAlignment), OnHorizontalAlignmentChanged));
public static void SetHorizontalAlignment(this UIElement element, HorizontalAlignment value)
{
element.SetValue(HorizontalAlignmentProperty, value);
}
[AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(UIElement))]
public static HorizontalAlignment GetHorizontalAlignment(this UIElement element)
{
return (HorizontalAlignment)element.GetValue(HorizontalAlignmentProperty);
}
private static void OnHorizontalAlignmentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var presenter = d.Parents().OfType<ContentPresenter>().FirstOrDefault();
if (presenter != null)
{
presenter.HorizontalAlignment = (HorizontalAlignment) e.NewValue;
}
}
private static IEnumerable<DependencyObject> Parents(this DependencyObject child)
{
var parent = VisualTreeHelper.GetParent(child);
while (parent != null)
{
yield return parent;
child = parent;
parent = VisualTreeHelper.GetParent(child);
}
}
}
It lets you do:
<Expander Header="{Binding ...}">
<Expander.HeaderTemplate>
<DataTemplate>
<!--Using a border here to show how width changes-->
<Border BorderBrush="Red" BorderThickness="1"
local:ParentContentPresenter.HorizontalAlignment="Stretch">
...
</Border>
</DataTemplate>
</Expander.HeaderTemplate>
</Expander>
Note that the use of the attached property is somewhat fragile as it assumes that there is a ContentPresenter
in the template.