wpf - 从上下文菜单项绑定(bind)到父控件

标签 wpf xaml binding

我有一个控件,该控件上有一个名为 SaveToClipboardCommand 的命令。我想将上下文菜单项命令绑定(bind)到该命令,以便在单击它时执行复制到剪贴板命令。

<Control x:Name="Control">
    <Control.ContextMenu>
        <ContextMenu>
            <MenuItem Command={"Bind to SaveToClipboardCommand here"} Header="Some Header" />
        </ContextMenu>
    </Control.ContextMenu/>
</Control>

控件(为了参数)定义如下:
partial class Control
{
      private ICommand _saveToClipboard;
      public ICommand SaveToClipboardCommand
      {
          get
          {
              if (_saveToClipboard == null)
              {
                  _saveToClipboard = new RelayCommand(
                         x=> SaveToClipboard());
              }
              return _saveToClipboard;
          }
     }
}

我尝试使用基于 RelativeSource 和 ElementName 的绑定(bind),但都失败了。我想要做的甚至可能吗?

谢谢!

最佳答案

编辑 (在展示了控件是如何暴露的之后):
嗯 ContextMenu 有点棘手,因为它实际上不是同一个可视化树的一部分。尝试这样做:

<MenuItem Command="{Binding Path=PlacementTarget.SaveToClipboardCommand,
    RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

原答案

Is this command exposed as a public property of the Control? If the command is actually exposed in a ViewModel hanging of the control's DataContext, to do the following:

Command={Binding ElementName=Control, Path=DataContext.SaveToClipboardCommand}

Can you show how this command is currently exposed?

关于wpf - 从上下文菜单项绑定(bind)到父控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3878620/

相关文章:

android - Xamarin 表单 : Problem with TwoWay Binding and StringFormat

c# - 获取winform列表框的所有项目

c# - 如何避免显示选择网络摄像头的对话框

xaml - Android 中不出现 ToolbarItem 图标

wpf - 如何在双击时禁用WPF TreeView中的树项展开/折叠

c# - 如何根据窗口更改对话框消息?

wpf - 将 WPF ComboBox 绑定(bind)到 ListBox DataTemplate 中的不同 ItemsSource

c# - 代码优化: Create a method for recurring procedures

c - 从 C 库头自动生成 Fortran 2003 绑定(bind)(使用 iso_c_bindings 内部模块)

c# - 将 WPF Button CommandParameter 绑定(bind)到 DataTemplate 中的 Button 本身