XAML数据绑定到另一个类

时间:2019-03-13 17:25:00

标签: c# wpf xaml data-binding

将TreeView(代码Tag="{Binding ParentData}"中的ChildButton的Tag属性绑定到TreeParent类的ParentData属性的最佳方法是什么?

<TreeView>
  <TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:TreeParent}" ItemsSource="{Binding Members}">
        <Button x:Name="ParentButton" Text="{Binding ParentName}">
        </Button>
    </HierarchicalDataTemplate>

    <DataTemplate DataType="{x:Type local:TreeChild}" ItemsSource="{Binding Members}">
        <Button x:Name="ChildButton" Text="{Binding ChildName}" Tag="{Binding ParentData}">
        </Button>
    </DataTemplate>
  </TreeView.Resources>
</TreeView>

xaml文件后面的.cs代码如下:

public class TreeParent
{
   public string ParentName { get; set; }
   public SomeDataClass ParentData { get; set; }
   public ObservableCollection<TreeChild> Members { get; set; }
}

public class TreeChild
{
   public string ChildName { get; set; }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

<Button x:Name="ChildButton" ... 
        Tag="{Binding DataContext.ParentData, 
             RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2}}" />