A Simple DataGrid Delete Button Using View Model / MVVM
Aug
14
Written by:
8/14/2010 2:40 PM

You may have looked at my Blog, “Deleting A Silverlight DataGrid Row With A Button On The Row” and thought, WHOA way too complicated!
Well, if you are willing to just have one delete Button, and not a delete Button on each row, this method is WAY simpler.
First, start off with a simple ICommand to handle the delete:
#region DeleteCommand
public ICommand DeleteCommand { get; set; }
public void Delete(object param)
{
// Clear the Comment
DeleteRIAComment((param as RIAComment).CommentID);
}
private bool CanDelete(object param)
{
return ((param as RIAComment) != null);
}
#endregion
It calls the following method to actually perform the delete, AND to remove the deleted item from the collection the DataGrid is bound to (this is what removes it from the DataGrid):
#region DeleteRIAComment
private void DeleteRIAComment(int CommentID)
{
// Call the Model to UpdateRIAComment the RIAComment
RIACommentsModel.DeleteRIAComment(CommentID, (Sender, EventArgs) =>
{
if (EventArgs.Error == null)
{
// Find the comment
var CommentInCollection =
(from comment in colRIAComments
where comment.CommentID == EventArgs.Result.CommentID
select comment).FirstOrDefault();
if (CommentInCollection != null)
{
// Remove it
colRIAComments.Remove(CommentInCollection);
}
// Show any errors
Errors = EventArgs.Result.Errors;
// Set the visibility of the Message ListBox
MessageVisibility = (Errors.Count > 0) ?
Visibility.Visible : Visibility.Collapsed;
}
});
}
#endregion
Expression Blend

In Expression Blend, drop a Button on the page.

In the Properties for the Button, click Advanced options next to Command (under Miscellaneous).

Select Data Binding…

In the Data Context section, select DeleteCommand, then click OK.

In the Properties for the Button, click Advanced options next to CommandParameter (under Miscellaneous).

Select Data Binding…

In the Element Property section, select the dataGrid, then SelectedItem, click OK.
Running The Project

When you build and run the project, you will notice that the Delete Button is disabled if you do not have a row selected on the DataGrid.
This is because the CanDelete method in the View Model returns False when no row is selected, and no parameter is passed to the method.

If you click on a row, the delete Button will be enabled, and you can click the Button to delete the row.
Download Source Code
You can download the full source code here:
http://silverlight.adefwebserver.com/files/RIADataGridDeleteConfirmation_SingleDeleteButton.zip