[英]Binding DependencyProperty in codebehind to CommandParameter
我试图通过命令参数在我的视图后面的代码中的依赖项属性将dp设置的属性thats发送到我的视图模型(通过datacontext绑定)。 闯入该属性时(ParentUserControl)似乎已正确初始化,但是我似乎无法发送它。 我已经尝试了下面的两个绑定
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyView}}}" />
</ContextMenu>
</DataGrid.ContextMenu>
和
<ContextMenu>
<MenuItem Command="{Binding CommandTest}"
CommandParameter="{Binding ParentUserControl, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />
</ContextMenu>
我正在使用mvvmlight中继命令,如下所示,但是方法test()中粘贴的参数始终为null
CommandTest = new RelayCommand<object>(x => test(x));
这是视图后面代码中附加的依赖项属性:
public static readonly DependencyProperty ParentUserControlProperty = DependencyProperty.Register(
"ParentUserControl", typeof(UserControl), typeof(MyView), new PropertyMetadata(default(UserControl)));
public UserControl ParentUserControl
{
get { return (UserControl) GetValue(ParentUserControlProperty); }
set { SetValue(ParentUserControlProperty, value); }
}
使用视图名称查找参数
CommandParameter="{Binding ElementName=MyViewName, Path=ParentUserControl}"
还要在MyView
上添加带有ViewModel的ParentUserControl
的虚拟绑定(并检查它是否在该级别上正常工作)。 我的意思是,尝试在视图模型上创建UserControl Parent
属性,绑定MyView的依赖项,然后尝试
CommandParameter="{Binding ElementName=MyViewName, Path=DataContext.Parent}"
在后一种情况下,由于它已经在视图模型中,因此您甚至不需要该参数。 顺便说一下,从MVVM设计模式的角度来看,您不应该将Control作为参数传递给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
(即DataGrid)和其Tag
(即MyView
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.