【问题标题】:Is there a cleaner way to Bind property to owner's DataContext?是否有更简洁的方法将属性绑定到所有者的 DataContext?
【发布时间】:2011-02-12 23:56:53
【问题描述】:

我有一些看起来像这样的代码:

<Expander Header="{Binding SelectedSlot.Name}"
          Visibility="{Binding ShowGroupSlot, Converter={StaticResource BooleanToVisibility}}">
    <Controls:GroupPrototypeSlotControl Slot="{Binding DataContext.SelectedSlot, 
        RelativeSource={RelativeSource Mode=FindAncestor,  AncestorType={x:Type Expander}}}" />
</Expander>

这可行,但插槽绑定的丑陋困扰着我。这是必需的,因为 GroupPrototypeSlotControl 有一个 GroupPrototypeViewModel 作为其 DataContext。如果我只是使用{Binding SelectedSlot},它会尝试在“子”ViewModel 上解决它,但失败了。我通过显式查看我的父控件的 DataContext 来解决这个问题。有没有更简洁的方法来进行这种类型的绑定?


编辑:我找到了一种更简洁的方法来解决我的问题,尽管它仍然感觉像是一个 hack。我修改了 GroupPrototypeSlotControl,使其具有顶级 LayoutRoot(在本例中为 StackPanel),然后将 LayoutRoot 的 DataContext 设置为 ViewModel,而不是设置整个控件的 DataContext。这允许我在使用控件的地方使用{Binding SelectedSlot} 语法(因为控件仍然具有父 DataContext),但代价是稍微增加了控件的复杂性。一般来说,这可能是自定义控件的更好模式,因为如果没有明确指定,控件的使用者希望 {Binding} 解析到它们的父 DataContext。

【问题讨论】:

    标签: c# wpf data-binding binding datacontext


    【解决方案1】:

    一种更简洁(更短)的方法是在您的Binding 中使用ElementName,如下所示:

    <Expander Header="{Binding SelectedSlot.Name}"
              x:Name="expander"
              Visibility="{Binding ShowGroupSlot, Converter={StaticResource BooleanToVisibility}}">
        <Controls:GroupPrototypeSlotControl Slot="{Binding DataContext.SelectedSlot, ElementName=expander}" />
    </Expander>
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      相关资源
      最近更新 更多