【问题标题】:Bind to parent object in xaml绑定到 xaml 中的父对象
【发布时间】:2012-02-06 01:17:27
【问题描述】:

我有一个这样的分层类

Part
  SubPart
     SubSubPart1
     SubSubPart2

我有一个由 SubSubPart 填充的控件,我想在该控件中显示有关父 SubPart 和 Part 的信息。我想在 xaml 中使用普通绑定来显示有关父部件的信息。

每个部分都有一个唯一的 ObjectId 作为属性,每个部分都有多个我要显示的属性。

控件只知道一个子子部分。

我意识到我可以写一个转换器

    public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture)
    {

        if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))

        { return "Design Part"; }
        else
        {

            IDataService applicationService = ServiceLocator.Current.GetInstance<IDataService>();
            IPartItem partItem = applicationService.GetEquipmentFromComponent(value.ToString());

            return partItem.PartData.Name;
        }
    }

并像这样应用它

<TextBlock Grid.Row="0" Grid.Column="1"
Text="{Binding Path=ObjectId,Converter={StaticResource partConverter}}" Margin="0,0,10,0">
</TextBlock>

但是我需要为父部件的每个属性编写一个转换器。任何解决方案。

【问题讨论】:

  • SubSubPart 对象没有对父 SubPart 对象的引用吗?如果他们这样做,您可以使用 Path=MySubPart.ParentPart.Name 之类的东西。

标签: wpf xaml binding converter


【解决方案1】:

您可以通过使用FindAncestor 绑定的FindAncestor 模式来完成您正在寻找的事情。

例如,TextBlock 的 text 属性如下:

Text="{Binding Path=ObjectId, RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type local:SubPart}, AncestorLevel=1}

其中local 将被声明为声明类SubPart 的命名空间。

您可以对Part 类遵循相同的模式,根据需要更改AncestorTypeAncestorLevel 属性。

【讨论】:

  • +1 虽然如果 ObjectId 存在于 SubPart 的 DataContext 而不是 SubPart 上的属性,那么您需要绑定到 DataContext.ObjectId
  • 感谢您的回答。对不起,如果我的解释不够好。子部分不是控件,它是控件绑定到的视图模型中的数据结构,并且控件只知道一个子子部分。
【解决方案2】:

使用转换器绑定控件的 DataContext 并更新转换器以仅返回父部分

<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding ObjectId}" DataContext="{Binding Converter={StaticResource partConverter}}" Margin="0,0,10,0" /> 

【讨论】:

  • 优秀。这是最终版本
猜你喜欢
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 2012-12-14
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多