Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a control, on that control is a command called SaveToClipboardCommand. I want to bind a context menu item command to that command so that when i click it, the copy to clipboard command is executed.

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

The control (for argument sake) is defined like this:

partial class Control
{
      private ICommand _saveToClipboard;
      public ICommand SaveToClipboardCommand
      {
          get
          {
              if (_saveToClipboard == null)
              {
                  _saveToClipboard = new RelayCommand(
                         x=> SaveToClipboard());
              }
              return _saveToClipboard;
          }
     }
}

I have tried using RelativeSource and ElementName based bindings but both are failing. Is what i am trying to do even possible?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

EDIT (after showing how the control is exposed): Well ContextMenu is somewhat tricky, because it's actually not part of the same visual tree. Try doing this:

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

Original answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...