Shortcut Delete Button on XamDataGrid

John Doe / Tuesday, July 14, 2009

I am goint to show you how to create a shortcut button to delete records in the last field of a XamDataGrid. To do that, I am going to use an UnboundField with a custom CellValuePresenterStyle. This style has a custom Template with the Delete Icon inside the ControlTemplate. When this Image is clicked, the selected DataRecord will be deleted.

 

<Style TargetType="{x:Type igDP:CellValuePresenter}" x:Key="deleteButtonStyle">

    <Setter Property="Visibility" Value="Collapsed"/>

    <Setter Property="Template">

        <Setter.Value>

            <ControlTemplate>

                <Image Source="X.png" HorizontalAlignment="Left"

                                      Width="20" Height="20"

                                      MouseLeftButtonDown="Image_MouseLeftButtonDown"/>

            </ControlTemplate>

        </Setter.Value>

    </Setter>

    <Style.Triggers>

        <DataTrigger Binding="{Binding Path=IsSelected}" Value="True">

            <Setter Property="Visibility" Value="Visible"/>

        </DataTrigger>

        <DataTrigger Binding="{Binding Path=IsActive}" Value="True">

            <Setter Property="Visibility" Value="Visible"/>

        </DataTrigger>

        <DataTrigger Binding="{Binding IsMouseOver,

                 RelativeSource={RelativeSource FindAncestor,

                 AncestorType={x:Type igDP:DataRecordPresenter}}}" Value="True">

            <Setter Property="Visibility" Value="Visible"/>

        </DataTrigger>

    </Style.Triggers>

</Style>

The next step is to handle the image's mouse left button down event like this:

private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

      //Force the record to become selected if it is not, so that DataPresenterCommand is fired

DataRecordPresenter dr = Utilities.GetAncestorFromType(sender as DependencyObject, typeof(DataRecordPresenter), false) as DataRecordPresenter;

dr.Record.IsSelected = true;

xamDataGrid1.ExecuteCommand(DataPresenterCommands.DeleteSelectedDataRecords);

}

You can find the complete project in this blog post's attachments.

I added some extra functionality to remove the MessageBox prompt message when you delete the record. You can do that by handling the RecordDeleting event and setting the DisplayPromptMessage to false in the args object.

testDeleteRecord.zip