我想在Expander控件中有一个自定义标头。我想要一个左对齐的标题文本和一个右对齐的图片:
<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>
不幸的是,标题是在一个元素内部渲染的,默认情况下不会延伸到水平方向。该元素是一个ContentPresenter控件,默认情况下它不会拉伸,因为它的HorisontalAlign值是Left。如果我将其更改为Stretch(我已在Snoop工具中完成此操作),则会根据需要呈现标题。但是如何从代码中更改它?
我尝试使用正确的HorizontalAlignment值将ContentPresenter样式添加到Expander资源,但不幸的是它不起作用。可能ContentPresenter应用了一些自定义样式,这就是为什么它没有抓住我的样式。我试过这样的话:
<Expander.Resources>
<Converters:TodoTypeToHeaderTextConverter x:Key="TodoTypeToHeaderTextConverter" />
<Style TargetType="ContentPresenter">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</Expander.Resources>
那么我还能尝试什么?
答案 0 :(得分:3)
尝试类似的东西:
XAML文件:
<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>
代码隐藏:
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;
}
}
辅助班:
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;
}
}
答案 1 :(得分:0)