2012-07-19 69 views
1

我想在扩展器控件中有一个自定义头。我想有左对齐一个标题文本和图片与右对齐:更改扩展器头ContentPresenter HorisontalAlign属性

<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> 

不幸的是,头不默认horizo​​ntaly舒展的元素中呈现。该元素是ContentPresenter控件,并且默认情况下它不会伸展,因为它的HorisontalAlign值是Left。如果我将它更改为Stretch(我已经在Snoop工具中完成了这项工作),那么头部会按照我的需要进行渲染。但是,我如何从代码中更改它?

我试着用正确的Horizo​​ntalAlignment值向Expander资源添加ContentPresenter样式,但不幸的是它不起作用。可能ContentPresenter应用了一些自定义样式,这就是为什么它没有抓住我的样式。我试过这样:

<Expander.Resources> 
    <Converters:TodoTypeToHeaderTextConverter x:Key="TodoTypeToHeaderTextConverter" /> 
    <Style TargetType="ContentPresenter"> 
     <Setter Property="HorizontalAlignment" Value="Stretch" /> 
    </Style> 
</Expander.Resources> 

那么我还能试试吗?

回答

2

尝试类似的东西:

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; 
     } 
    }