C# 将codebehind中的DependencyProperty绑定到CommandParameter
我正试图通过命令参数将dp设置的属性发送到我的viewmodel(通过datacontext绑定),这是视图代码隐藏中的一个依赖属性。该属性(ParentUserControl)在破译时似乎已正确初始化,但我似乎无法发送它。我试过下面的两种绑定C# 将codebehind中的DependencyProperty绑定到CommandParameter,c#,wpf,C#,Wpf,我正试图通过命令参数将dp设置的属性发送到我的viewmodel(通过datacontext绑定),这是视图代码隐藏中的一个依赖属性。该属性(ParentUserControl)在破译时似乎已正确初始化,但我似乎无法发送它。我试过下面的两种绑定 <DataGrid.ContextMenu> <ContextMenu> <MenuItem Command="{Binding CommandTest}" Com
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyView}}}" />
</ContextMenu>
</DataGrid.ContextMenu>
使用视图的名称查找参数
CommandParameter="{Binding ElementName=MyViewName, Path=ParentUserControl}"
还可以在MyView
及其ViewModel上添加一个虚拟绑定ParentUserControl
(并检查它是否在该级别工作)。
我的意思是,尝试在视图模型上创建一个usercontrolparent
属性,绑定MyView的依赖项,然后重试
CommandParameter="{Binding ElementName=MyViewName, Path=DataContext.Parent}"
在后一种情况下,因为它已经在视图模型中,所以您甚至不需要该参数。顺便说一下,从MVVM设计模式的角度来看,您不应该将控件作为参数传递给ViewModel 您应该使用以下内容:
<DataGrid
Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type MyView}}}">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding PlacementTarget.Tag.ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ContextMenu}}}" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
将
DataGrid
的标记绑定到MyView
。在MenuItem
中搜索ContextMenu
,使用其PlacementTarget
(即数据网格)及其标记(即MyView
)。ContextMenu
会破坏可视树,如前所述,您可以使用PlacementTarget
缩小差距。我不确定这是否是我要寻找的,该命令已绑定到viewmodel并且工作正常,这是我遇到困难的命令参数,尽管我在CommandParameter上尝试过,我也试过这个,但不幸的是它还是没有通过。对不起,我不明白你说的虚拟绑定是什么意思,你能解释一下吗。
CommandParameter="{Binding ElementName=MyViewName, Path=ParentUserControl}"
CommandParameter="{Binding ElementName=MyViewName, Path=DataContext.Parent}"
<DataGrid
Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type MyView}}}">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding PlacementTarget.Tag.ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ContextMenu}}}" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>