2012-05-10 75 views
0

我有一個可以停靠在DockPanel左側或右側的StackPanel。 StackPanel中的項目應該像祖先一樣停靠在同一側。對於測試,我得到了Visual Tree中的祖先的名稱,但我不知道如何綁定到Docking.Dock。提前致謝。綁定到祖先StackPanel DockPanel.Dock

<DockPanel> 
    <StackPanel x:Name="RightHandContainer" DockPanel.Dock="Right"> 
    <v:MyUsercontrol TextCaption="Hard-Coded Alignment Works" Alignment="Right" /> 
    <v:MyUsercontrol TextCaption="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel, AncestorLevel=1}, Path=Name}"     
         Alignment="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel, AncestorLevel=1}, Path=Docking.Dock}" /> 
    <!-- TextCaption is is a dependencyproperty of Type string, works fine ... my Text object automatically gets 'RightHandContainer' --> 
    <!-- Alignment is is a dependencyproperty of Type Dock, like Docking.Dock ... Binding will not work :(--> 
    </StackPanel> 
</DockPanel> 

回答

0

一種方法是創建一個值轉換器。將屬性綁定到堆棧面板本身,並抓住valueConverter中的停靠欄並返回所需的任何內容。事情是這樣的:

<Window.Resources> 
    <app:TestConverter x:Key="TestConverter" /> 
</Window.Resources> 
<DockPanel> 
    <StackPanel x:Name="RightHandContainer" DockPanel.Dock="Right"> 
     <TextBlock Text="Test" HorizontalAlignment="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel, AncestorLevel=1}, Converter={StaticResource TestConverter}}" /> 
    </StackPanel> 
</DockPanel> 

轉換器:

public class TestConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     HorizontalAlignment alignment = HorizontalAlignment.Left; 

     StackPanel stackPanel = value as StackPanel; 
     if (stackPanel != null) 
     { 
      Dock dock = DockPanel.GetDock(stackPanel); 
      switch (dock) 
      { 
       case Dock.Left: alignment = HorizontalAlignment.Left; break; 
       case Dock.Right: alignment = HorizontalAlignment.Right; break; 
      } 
     } 
     return alignment; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

我用水平對齊方式,但您可以回到任何你需要。

+0

很好,謝謝。 – LaWi