Search code examples
c#wpfbuttondatagridcopy

How to specify area to copy? C# WPF Datagrid


I have Copy button near each of the row, and I want the text contained in the row near button to be copied when the button is pressed.

I can't understand how to specify what needs to be copied by pressing a button?

Image of table, and what exactly I want to copy: here is picture


Solution

  • The simplest solution is to use the ApplicationCommands.Copy command. This command is handled by the DataGrid. It will automatically copy the selected row to the clipboard.

    <DataGrid>
      <DataGrid.Columns>
        <DataGridTextColumn Header="Order" Binding="{Binding Order}" />
    
        <DataGridTemplateColumn Header="Copy Action">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <Button Content="Copy" 
                      Command="{x:Static ApplicationCommands.Copy}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
      </DataGrid.Columns>
    </DataGrid>