gpt4 book ai didi

wpf - 将列表框项内的命令绑定(bind)到 View 模型父级上的属性

转载 作者:行者123 更新时间:2023-12-03 12:01:48 25 4
gpt4 key购买 nike

我已经为此工作了大约一个小时,并查看了所有相关的 SO 问题。

我的问题很简单:

我有 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>

该列表显示所有项目都很好,但是对于我的生活,无论我为命令尝试什么都行不通:
<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 Error: 4 : Cannot find source for binding with reference .....


更新
我正在这样设置我的 ViewModel 吗?没想到这很重要:
 <Window.DataContext>
<Binding Path="HomePage" Source="{StaticResource Locator}"/>
</Window.DataContext>

我使用了 MVVMLight 工具包中的 ViewModelLocator 类,它具有魔力。

最佳答案

尝试这样的事情

<Button Command="{Binding DataContext.YourCommand,RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"

他在列表框中找不到您的命令绑定(bind),因为您设置的数据上下文与该列表框的 View 模型不同

关于wpf - 将列表框项内的命令绑定(bind)到 View 模型父级上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com