【问题标题】:WPF: Accessing two DataContexts in the same controlWPF:在同一个控件中访问两个 DataContext
【发布时间】:2010-12-21 13:09:02
【问题描述】:

我正在使用 MVVM 方法,并且我的 ViewModel 中有一个名为 DatabasesSubFrame 的对象,它是 DataTemplated 以显示 ListBox。我想在ListBox 下方显示一个Button,它绑定到当前的SelectedItem,以及DatabasesSubFrame 对象上的一个属性,即DataTemplated。

我知道如何引用当前选定的项目,方法是将DataContext 设置在与ListBox 共享的祖先上并使用{Binding /}。在此示例中,共享祖先是 StackPanel。如果DataContext 没有显式设置在那里,我可以通过执行{Binding SomeProperty} 轻松绑定到DatabasesSubFrame 对象上的属性。但是,如果我在显式设置的DataContext 中执行{Binding SomeProperty},它指的是错误的DataContext

如何在此处访问“原始”DataContext?我尝试弄乱RelativeSources 和TemplatedParents,但不知道如何适应它们。

<DataTemplate DataType="{x:Type VM:DatabasesSubFrame}">
  <StackPanel DataContext="{Binding Databases}" >
     <ListBox Name="DbInfoBox" 
              ItemsSource="{Binding}"
              IsSynchronizedWithCurrentItem="True">
         <ListBox.ItemTemplate>
              <DataTemplate>
                  <Label Content="{Binding ShortName}"/>
              </DataTemplate>
         </ListBox.ItemTemplate>
     </ListBox>
     <!-- Problem: The Command and V:CreateCommandBinding.Command are set incorrectly here. How do I access OpenDbCommand from the top-level DataTemplate's DataContext? -->
     <Button Content="Open Database"
             CommandParameter="{Binding /}"
             Command="{Binding ???, Path=OpenDbCommand.Command}"
             V:CreateCommandBinding.Command="{Binding ???, Path=DataContext.OpenDbCommand}"/>
   </StackPanel>
</DataTemplate>

【问题讨论】:

  • 看起来我可以修改我的数据项以保存对父视图模型对象的引用,但这似乎有点 hacky。

标签: c# .net wpf data-binding datatemplate


【解决方案1】:

我认为this question 会帮助你找到你的答案。另一个技巧是将窗口的名称设置为“Root”之类的名称。然后,您可以使用以下方法获取窗口的原始数据上下文:

{Binding ElementName=Root, Path=DataContext.MyViewModelsProperty}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2013-03-08
    • 2011-02-16
    • 2012-08-04
    相关资源
    最近更新 更多