Copy and paste commands with WPF buttons

18,588

You can’t use command this way! The Command (in the way you use it) should be inside a Menu or Toolbar.
By the way, you don’t need those click event handler since you are going to use Commands!
I recommend you to try add DelegateCommand to the ViewModel and let that delegate call ApplicationCommads.

I highly recommend you to read this http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
But as a quick solution for you try the following (important: remember that you need to have some text selected in your TextBox then Copy and Cut will be enabled):

<StackPanel  HorizontalAlignment="Left" VerticalAlignment="Top">

  <ToolBar>
    <Button Content="Cut" Command="ApplicationCommands.Cut" Height="23" Width="75"/>
    <Button Content="Copy" Command="ApplicationCommands.Copy" Height="23" Width="75"/>
    <Button Content="Paste" Command="ApplicationCommands.Paste" Height="23" Width="75"/>
  </ToolBar>

  <TextBox Height="23" Name="textBox1" Width="120"/>

</StackPanel>
Share:
18,588

Related videos on Youtube

TMan
Author by

TMan

Updated on June 04, 2022

Comments

  • TMan
    TMan almost 2 years

    I have created a toolbar that has buttons.

    Of the buttons 3 of them are cut copy and paste. I set the command of each of those buttons to cut copy and paste on the properties but when I go run the program none of the buttons are even clickable. Are they disabled I'm guessing? I'm trying to copy and paste from textbox to textbox in a tabcontrol. Any help is appreciated.

    <Style TargetType="{x:Type Button}" x:Key="textBoxCommands">
      <Setter Property="Content" 
              Value="{Binding RelativeSource={RelativeSource Self}, 
                              Path=Command.Text}" />
      <Setter Property="CommandTarget" 
              Value="{Binding ElementName=textBox}" />
    </Style>
    
    <Button x:Name="btnCut" 
            Click="btnCut_Click">
      <Image Source="Icons/Cut.png" ToolTip="Cut" />
    </Button>
    <Button x:Name="btnCopy" 
            Click="btnCopy_Click" 
            Command="ApplicationCommands.Copy"
            Style="{StaticResource textBoxCommands}">
      <Image Source="Icons/Copy.png" ToolTip="Copy" />
    </Button>
    <Button x:Name="btnPaste" 
            Click="btnPaste_Click" 
            Command="ApplicationCommands.Paste"
            Style="{StaticResource textBoxCommands}" > 
      <Image Source="Icons/Paste.png" ToolTip="Paste" />
    </Button>
    
  • TMan
    TMan over 12 years
    Thanks for the reply. I understand what those commands can be used for. I feel stupid asking this question but I'm new to all this. what is viewMode?
  • Fred Jand
    Fred Jand over 12 years
    It was not a stupid question! Sorry I had a typo it was “ViewModel” (I had written ViewMode). I added some code to my answer