2014-01-30 52 views
0

试图在我的程序中将Command绑定到MenuItem,我发现Commands不像MenuItems那样与其他控件一起使用。我一直在使用this作为指南,但迄今为止还没有运气。基本上我的目标是在单击MenuItem时运行Command如何在MenuItems上执行命令

这是我查看之前提到的帖子后的xaml。我Command被称为CreateFiles

<MenuItem Header="{DynamicResource save}" Command="{Binding Path=PlacementTarget.DataContext.CreateFiles, RelativeSource={RelativeSource AncestorType=ContextMenu}}" /> 

Command在窗口的视图模型被创建并宣布正常人一样,但我无论如何都会张贴:

private ICommand _createFiles; 

public MainWindowViewModel() 
{ 
    _createFiles = new Command(createFiles_Operations); 
} 

public ICommand CreateFiles { get { return _createFiles; } } 
private void createFiles_Operations() 
{ 

} 

为了测试是否不是我Command工作我在第一个护腕处设置了一个断点。到目前为止,当点击MenuItem时,程序还没有停在这个中断点。

由于此方法似乎不起作用,我该怎么做CommandsMenuItems一起使用?

更新:Command改为ICommand

更新2:ContextMenu & Button XAML:

<Button Click="Button_Click_1" Margin="5,4,0,0" Name="Button_1" Height="55" VerticalAlignment="Top" HorizontalAlignment="Left" Width="55" BorderBrush="Black">... 

<ContextMenu x:Name="MainContextMenu" MouseLeave="ContextMenuMouseLeave" Background="White" BorderBrush="#FF959595" SnapsToDevicePixels="False">... 
+0

在哪里菜单项申报? – Botonomous

+0

它就在XAML中。它是'' - >'' –

回答

0

您需要设置Mode of RelativeSourceFindAncestor得到ContextMenu

<MenuItem Header="{DynamicResource save}" 
      Command="{Binding Path=PlacementTarget.DataContext.CreateFiles, 
      RelativeSource={RelativeSource Mode=FindAncestor, 
              AncestorType=ContextMenu}}" /> 

您已将PlacementRectangle属性设置为指向其本身,即ContextMenu。不要设置该属性,ContextMenuService内部设置PlacementRectangle到它应用的元素(在你的情况下它将是按钮)。

从ContextMenu中删除此PlacementRectangle="{Binding RelativeSource={RelativeSource Self}}"

它应该是:

<ContextMenu x:Name="MainContextMenu" 
      MouseLeave="ContextMenuMouseLeave" Background="White" 
      BorderBrush="#FF959595" SnapsToDevicePixels="False"> 
+0

的一部分我已将我的代码更改为此。有没有可能有我需要的其他东西?我的程序不会停止在'createFiles_Operations()'的中断点。 –

+0

'CreateFiles'的返回类型应该是'ICommand'。什么是命令?您是否能够在输出窗口中看到任何绑定错误? –

+0

Button的DataContext是否正确指向'MainWindowViewModel'? –