Wpf 绑定到StackPanel DockPanel.Dock
我有一个StackPanel,可以停靠在DockPanel内部的左侧或右侧。StackPanel中的项目应该像祖先一样停靠在同一侧。为了进行测试,我在可视化树中得到了祖先的名字,但我不知道如何绑定到Docking.Dock。提前谢谢Wpf 绑定到StackPanel DockPanel.Dock,wpf,binding,stackpanel,dockpanel,relativesource,Wpf,Binding,Stackpanel,Dockpanel,Relativesource,我有一个StackPanel,可以停靠在DockPanel内部的左侧或右侧。StackPanel中的项目应该像祖先一样停靠在同一侧。为了进行测试,我在可视化树中得到了祖先的名字,但我不知道如何绑定到Docking.Dock。提前谢谢 <DockPanel> <StackPanel x:Name="RightHandContainer" DockPanel.Dock="Right"> <v:MyUsercontrol TextCaption="Hard-C
<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>
一种方法是创建一个值转换器。将属性绑定到stackpanel本身,抓住valueconverter内的dock并返回所需的任何内容。大概是这样的:
<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();
}
}