【问题标题】:How to implement commands on MenuItems如何在 MenuItems 上实现命令
【发布时间】:2014-02-23 06:39:10
【问题描述】:

在我的程序中尝试将Command 绑定到MenuItem 时,我发现Commands 不能与MenuItems 一起使用,就像它们与其他控件一样。我一直使用this 帖子作为指导,但到目前为止还没有运气。基本上我的目标是在点击MenuItem 时运行Command

这是我查看前面提到的帖子后的 xaml。我的CommandCreateFiles

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

我的Command 是在窗口的 ViewModel 中创建的,并且声明正常,但我还是会发布它:

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

【问题讨论】:

  • menuItem 声明在哪里?
  • 它就在 XAML 中。它是&lt;Button.ContextMenu&gt; 的一部分 --> &lt;ContextMenu&gt;

标签: c# wpf data-binding command menuitem


【解决方案1】:

您需要将Mode of RelativeSource 设置为FindAncestor 以获取ContextMenu

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

您已将PlacementRectangle 属性设置为引用自身,即ContextMenu。不要设置该属性,ContextMenuService 在内部将 PlacementRectangle 设置为应用它的元素(在您的情况下它将是 Button)。

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

应该是:

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

【讨论】:

  • 我已经把我的代码改成了这个。有没有机会我需要其他东西?我的程序没有在createFiles_Operations() 的断点处停止。
  • CreateFiles 的返回类型应为ICommandCommand 是什么?您能在输出窗口中看到任何绑定错误吗?
  • Button的DataContext指向MainWindowViewModel是否正确?
  • 输出窗口中没有绑定错误。我已更新我的问题以显示 ICommand 而不是 Command。就 DataContext 而言,这是在窗口的构造函数中设置的,如下所示:DataContext = App.MainWindowViewModel = new MainWindowViewModel();。我没有单独设置 Button 的 DataContext。
  • 我能想到的唯一原因是 Button 没有从窗口或 UserControl 继承 DataContext。否则代码看起来非常完美。
猜你喜欢
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
相关资源
最近更新 更多