Search code examples
c#wpfrouted-commands

How to set WPF ApplicationCommands in code behind


I know how to set default ApplicationCommands commands in WPF in order to enable simple cut, copy, and paste operations via ContextMenu. However I need to be able to do this in the code behind so that I can assign the commands dynamically as my TextBoxes are created.

How can I recreate this very simple WPF code in the code behind:

<TextBox x:Name="txtTagName" Style="{StaticResource TextBoxStyle}">
    <TextBox.ContextMenu>
        <ContextMenu Style="{StaticResource DefaultContextMenuStyle}">
            <MenuItem x:Name="cmCut" Header="Cut" Command="ApplicationCommands.Cut" />
            <MenuItem x:Name="cmCopy" Header="Copy" Command="ApplicationCommands.Copy" />
            <MenuItem x:Name="cmPaste" Header="Paste" Command="ApplicationCommands.Paste" />
        </ContextMenu>
    </TextBox.ContextMenu>
</TextBox>

Solution

  • you could do something like:

    this.cmCut.Command = ApplicationCommands.Cut;