我想通过命令参数在我的视图后面的代码中的依赖属性发送由dp设置的属性给我的viewmodel(通过datacontext绑定)。该属性(ParentUserControl)似乎在进入时正确初始化,但是我似乎无法发送它。我已经试过下面代码隐藏的绑定依赖属性到CommandParameter
<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中继命令如下所示然而在该方法中测试pased()的参数总是空
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); }
}
'ContextMenu'打破了视觉树,你可以用'PlacementTarget'来解决这个问题,就像[这里]解释的一样(http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or -上下文菜单)。 – bab7lon
我不确定这是我在找什么,命令已经绑定到viewmodel并且工作正常,它的命令参数我遇到了困难 –
尽管我在CommandParameter上尝试了它,但没有运气。 –