Search code examples
c#wpfgridviewoverridingcopy-paste

Override copy past functionality of a WPF grid view


I have a WPF DataGrid with one column:

 <DataGrid Name="myGRID">
    <DataGrid.Columns>
        <DataGridTextColumn Header="myHeader Binding="{Binding myObservableCollection}">
            <DataGridTextColumn.HeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Setter Property="HorizontalContentAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.HeaderStyle>
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="HorizontalAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.ElementStyle>
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="{x:Type TextBox}">
                    <EventSetter Event="TextChanged" Handler="tbx_ConcernEnter_TextChanged"/>
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

Now i want to override the paste function of the rows. When i use:

<DataGrid>
<CommandBinding Command="Paste" Executed="CommandBinding_Executed"/>
</DataGrid>

this seems to be the override for the whole GridView but not for a specific row.

Do you know how to override this?


Solution

  • The TextBox in the CellEditingTemplate "swallows" the paste command. But you could handle the Loaded event for the TextBox and hook up a Pasting event handler to it:

    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBox}">
            <EventSetter Event="TextChanged" Handler="tbx_ConcernEnter_TextChanged"/>
            <EventSetter Event="Loaded" Handler="TextBox_Loaded" />
        </Style>
    </DataGridTextColumn.EditingElementStyle>
    

    private void TextBox_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        DataObject.AddPastingHandler(textBox, OnPaste);
    }
    
    private void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        //paste detected...
    }