Wpf如何绑定祖先的viewmodel中的命令 [英] Wpf how to bind to commands in the ancestor's viewmodel
问题描述
我的英语不好,所以我不知道我是否可以说清楚,对不起。
我真的不知道如何在做一些研究时解释它。
目前,我有一个名为ToolPathPage的UserConstrol页面,它包含另一个名为ToolPathDataControl的UserControl,它只包含一个DataGrid。 />
现在我想将ToolPathPageViewModel中的Command绑定到ToolPathDataControl.xaml中的MenuItem。
我尝试过:
< DataGrid.ContextMenu >
< ContextMenu >
< MenuItem 标题 = 清除 命令 = {Binding RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:Type local:ToolPathPage},AncestorLevel = 1},Path = DataContext。(viewModel:ToolPathPageViewModel.Clear_AllCommand }} / >
< / ContextMenu >
< / DataGrid.ContextMenu >
在输出窗口中,它显示:
无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='mTracke r.ToolPathPage',AncestorLevel ='1''。 BindingExpression:路径= DataContext的(0);的DataItem = NULL; target元素是'MenuItem'(Name =''); target属性是'Command'(类型'ICommand')
感谢 @ RichardDeeming ,我得到了我的最终解决方案:
< DataGrid 标记 = {Binding RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:Type local:ToolPathPage },Path = DataContext。(viewModel:ToolPathPageViewModel.Clear_AllCommand)} >
< DataGrid.ContextMenu >
< ContextMenu >
< MenuItem < span class =code-attribute>标题 = 清除 命令 = {Binding PlacementTarget.Tag,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = ContextMenu}} / >
< / ContextMenu >
< / DataGrid.ContextMenu >
< / DataGrid > < /跨度>
My English is bad, so I don't know if I can make it clear, sorry about that.
And I really don't know how to explain it when trying to do some research.
Currently, I have a page which is a UserConstrol called "ToolPathPage", and it contains another UserControl called "ToolPathDataControl" which contains nothing but a DataGrid.
Now I want to bind a Command in the ToolPathPageViewModel to a MenuItem in ToolPathDataControl.xaml.
What I have tried:
<DataGrid.ContextMenu>
<ContextMenu >
<MenuItem Header="Clear" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ToolPathPage},AncestorLevel= 1}, Path=DataContext.(viewModel:ToolPathPageViewModel.Clear_AllCommand)}"/>
</ContextMenu>
</DataGrid.ContextMenu>
In the Output window it says:
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='mTracker.ToolPathPage', AncestorLevel='1''. BindingExpression:Path=DataContext.(0); DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
Thanks to @RichardDeeming, I got my final solution:
<DataGrid Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ToolPathPage}},Path=DataContext.(viewModel:ToolPathPageViewModel.Clear_AllCommand)}"> <DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="Clear" Command="{Binding PlacementTarget.Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/> </ContextMenu> </DataGrid.ContextMenu> </DataGrid>
这篇关于Wpf如何绑定祖先的viewmodel中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!