2017-02-26 71 views
0

我想通过命令参数在我的视图后面的代码中的依赖属性发送由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); } 
} 
+0

'ContextMenu'打破了视觉树,你可以用'PlacementTarget'来解决这个问题,就像[这里]解释的一样(http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or -上下文菜单)。 – bab7lon

+0

我不确定这是我在找什么,命令已经绑定到viewmodel并且工作正常,它的命令参数我遇到了困难 –

+0

尽管我在CommandParameter上尝试了它,但没有运气。 –

回答

0

你应该使用这样的事情:

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

您绑定的标签DataGridMyView。在MenuItem中,您为ContextMenu使用它的PlacementTarget(它是DataGrid)及其Tag(它是MyView)。

+0

你的传奇,完美的工作谢谢你! –

0

使用名称的视图,找到参数

CommandParameter="{Binding ElementName=MyViewName, Path=ParentUserControl}" 

另外添加一个虚拟的MyView其视图模型的ParentUserControl结合(并检查其是否在该级别的工作)。 我的意思是,尝试创建视图模型一个UserControl Parent特性,结合MyView的的相关性,然后尝试

CommandParameter="{Binding ElementName=MyViewName, Path=DataContext.Parent}" 

在后一种情况下,因为它已经在视图模型,也许你甚至都不需要参数。顺便说一句,从MVVM设计模式的角度来看,你不应该传递控制作为参数传递给视图模型...

+0

我也试过这个,但不幸的是它仍然通过null –

+0

对不起,我不明白你是什么意思的虚拟绑定,你能解释更多请。 –