1
votes

I have a DataGrid displaying child data nested within an outer parent DataGrid and I want to copy all selected cells (parent and child).

I have included the following context menu in my outer datagrid which successfully copies the parent data:

<DataGrid Grid.Column="2" Name="dgCalls" ItemsSource="{Binding FoundCallsList}" 
          AutoGenerateColumns="False" Background="{DynamicResource WindowBackgroundBrush}" 
          IsReadOnly="True">

  <DataGrid.ContextMenu>
    <ContextMenu>
      <MenuItem Command="Copy">
        <MenuItem.Icon>
          <Image Source="..\resources\CopyHS.png" />
        </MenuItem.Icon>
      </MenuItem>
    </ContextMenu>
  </DataGrid.ContextMenu>
  ...

I tried adding this code to the inner DataGrid, but to no avail. If I select the parent and child data and copy it, when pasting I only get the outer data. If I select only the child data, when pasting I get a blank line.

Xaml for the inner grid, if it helps:

<DataGrid.RowDetailsTemplate>
  <DataTemplate>
    <DataGrid ItemsSource="{Binding CallQueries}" AutoGenerateColumns="False">
      <DataGrid.Columns>
        <DataGridTemplateColumn Header="Question" Width="450">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock VerticalAlignment="Stretch" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding QueryQuestion}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
      </DataGrid.Columns>
    ...  

How do I copy data from both innner (child) and outer (parent) DataGrid?

1
Can you provide sample code? - a.azemia
@a.azemia The xaml is using the built-in ApplicationCommands.Copy property which uses the implementation in the control. There is no .cs code with this issue (though I'm expecting to have to write some). - mcalex

1 Answers

0
votes

I would go about this in two approaches :

The first :

Try creating the context menu as a resource and assigning it (The same instances) to both the parent and child DataGrids , this is based on my assumption that MS Window's default behavior is copying selection of the associated items.

The second:

if the first does not work . create a behavior for the ContextMenu which extracts the PlacementTarget (i.e your parent DataGrid) and then runs on it's Items ( i.e. Rows ) and extracts a DataGrid ( you child DataGrids) from them

This can be achieved by using the VisualTreeHelper or Properties exposed from the Elements them self's or a combination of the two.