【问题标题】:Binding to ancestor StackPanel DockPanel.Dock绑定到祖先 StackPanel DockPanel.Dock
【发布时间】:2012-05-10 12:13:52
【问题描述】:

我有一个 StackPanel,可以停靠在 DockPanel 的左侧或右侧。 StackPanel 中的项目应该像祖先一样停靠在同一侧。对于测试,我在 Visual Tree 中获得了祖先的名称,但我不知道如何绑定到 Docking.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>

【问题讨论】:

    标签: wpf binding stackpanel dockpanel relativesource


    【解决方案1】:

    一种方法是创建一个价值转换器。将属性绑定到 stackpanel 本身,然后在 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();
        }
    }
    

    我使用了水平对齐,但你可以返回任何你需要的东西。

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 2011-10-13
      • 1970-01-01
      • 2011-03-25
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多