2012-07-19 92 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; 
     } 
    }