将列表框项内的命令绑定到视图模型父级上的属性 [英] binding a command inside a listbox item to a property on the viewmodel parent
问题描述
我已经为此工作了大约一个小时,并查看了所有相关的 SO 问题.
I've been working on this for about an hour and looked at all related SO questions.
我的问题很简单:
我有 HomePageVieModel:
I have HomePageVieModel:
HomePageVieModel
+IList<NewsItem> AllNewsItems
+ICommand OpenNews
我的标记:
<Window DataContext="{Binding HomePageViewModel../>
<ListBox ItemsSource="{Binding Path=AllNewsItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock>
<Hyperlink Command="{Binding Path=OpenNews}">
<TextBlock Text="{Binding Path=NewsContent}" />
</Hyperlink>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
列表显示所有项目都很好,但对于我的生活,无论我为命令尝试什么都行不通:
The list shows fine with all the items, but for the life of me whatever I try for the Command won't work:
<Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel, AncestorLevel=1}}">
<Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=FindAncestor}**}">
<Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=TemplatedParent}**}">
我总是得到:
System.Windows.Data 错误:4:无法找到绑定引用的源.....
System.Windows.Data Error: 4 : Cannot find source for binding with reference .....
更新我正在像这样设置我的 ViewModel?没想到这会很重要:
Update I am setting my ViewModel like this? Didn't think this would matter:
<Window.DataContext>
<Binding Path="HomePage" Source="{StaticResource Locator}"/>
</Window.DataContext>
我使用了 MVVMLight 工具包中的 ViewModelLocator 类,它发挥了神奇的作用.
I use the ViewModelLocator class from the MVVMLight toolkit which does the magic.
推荐答案
这里有两个问题对您不利.
There's two issue working against you here.
DataTemplate
的 DataContext
设置为模板显示的项目.这意味着您不能只使用绑定而不设置源.
The DataContext
for the DataTemplate
is set to the item the template is displaying. This means you can't just use binding without setting a source.
另一个问题是模板意味着该项目在技术上不是逻辑树的一部分,因此您无法搜索 DataTemplate
节点之外的祖先.
The other issue is that the template means the item is not technically part of the logical tree, so you can't search for ancestors beyond the DataTemplate
node.
要解决此问题,您需要将绑定范围置于逻辑树之外.您可以使用在此处定义的 DataContextSpy.
To solve this you need to have the binding reach outside the logical tree. You can use a DataContextSpy defined here.
<ListBox ItemsSource="{Binding Path=AllNewsItems}">
<ListBox.Resources>
<l:DataContextSpy x:Key="dataContextSpy" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock>
<Hyperlink Command="{Binding Source={StaticResource dataContextSpy}, Path=DataContext.OpenNews}" CommandParameter="{Binding}">
<TextBlock Text="{Binding Path=NewsContent}" />
</Hyperlink>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这篇关于将列表框项内的命令绑定到视图模型父级上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!