【发布时间】: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