最快的方法是将header的宽度绑定到整个展开器的宽度。
<Expander IsExpanded="True">
<Expander.Header>
<Grid Width="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type Expander}},
Path=ActualWidth}"
Height="50">
<Rectangle Fill="Red"></Rectangle>
</Grid>
</Expander.Header>
<Rectangle Fill="Red"></Rectangle>
</Expander>
但这不是一种精确的方法,因为您的箭头也需要一些空间,并且您可以看到标题比您需要的要宽一些。
您可以覆盖扩展器标头的标准模板 (HeaderTemplate)。
更新
我找到了使用the code-behind file 的可能解决方案(所有学分归@kmatyaszek)。
添加一个帮助类来找到我们需要改变宽度的控件。它检查父控件的整个可视树并返回我们正在寻找的类型的子控件。
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;
}
}
添加一个处理程序来处理加载事件。它更改了ContentPresenter 实例的HorizontalAlignment 属性:
private void expander_Loaded(object sender, RoutedEventArgs e)
{
var tmp = VTHelper.FindChild<ContentPresenter>(sender as Expander);
if (tmp != null)
{
tmp.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
}
}
将此处理程序附加到扩展器:
<Expander IsExpanded="True" Loaded="expander_Loaded">
此方法使用代码隐藏,但不适用于任何数据(或 ViewModel)。它只改变控件的视觉外观。