【问题标题】:Escaping a WPF DataContext转义 WPF 数据上下文
【发布时间】:2014-10-30 16:37:12
【问题描述】:

我尤其是 MVVM 的新手。

我有以下 XAML 代码:

<ListBox x:Name="lsbTriggers" ItemsSource="{Binding SelectedProductPart.TriggerViewModels}">
            <ListBox.ItemTemplate>
                <HierarchicalDataTemplate >
                    <ComboBox SelectedItem="{Binding WatchedVariable}" 
                     ItemsSource="{Binding SelectedProductPart.AllVariables}" >                            
                    </ComboBox>
                </HierarchicalDataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我正在尝试创建一个列表,其中包含每个 TriggerViewModel 的组合框。

组合框的选定项由 TriggerViewModel 的 WatchedVariable 属性确定。

但是,我希望组合框的 ItemsSource 是 SelectedProductPart 对象提供的变量列表。 我似乎无法做到这一点,因为数据上下文已经“放大”,如果你愿意的话,在 TriggerViewModels 上,因为它是列表的 ItemsSource。

我尝试在组合框内创建一个新的 DataContext,但这似乎创建了两个断开连接的 DataContext,其中更改组合框的值不会导致 TriggerViewModel 的 WatchedVariable 发生变化。

有没有办法可以转义当前的 DataContext,以便我可以访问 SelectedProductPart 的 AllVariables 列表?

【问题讨论】:

标签: c# wpf xaml mvvm


【解决方案1】:

您必须使用Binding显式 方式指定其来源(通过ElementNameSourceRelativeSource)。在这种情况下,我们使用RelativeSource。它有助于沿着可视化树向上并根据其类型定位源 (AncestorType):

<ListBox x:Name="lsbTriggers" ItemsSource="{Binding SelectedProductPart.TriggerViewModels}">
     <ListBox.ItemTemplate>
       <HierarchicalDataTemplate >
          <ComboBox SelectedItem="{Binding WatchedVariable}" 
               ItemsSource="{Binding DataContext.SelectedProductPart.AllVariables,
                     RelativeSource={RelativeSource AncestorType=ListBox}}" >
          </ComboBox>
       </HierarchicalDataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

注意Path 前面带有DataContext

【讨论】:

  • 完美运行。谢谢!
猜你喜欢
  • 2019-04-13
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多