OpenLightGroup Blog

rss

Blogs from OpenLightGroup.net


Raising a Button Click in a DataGrid using MVVM

clip_image001

I wanted to put a button that would set the current comment to “****” when the button was clicked. I am using View Model (MVVM) and normally you would need to resort to using code behind.

Actually it is simple to do.

clip_image003

Create a column and then Edit the Style

clip_image005

When the Style comes up, Edit the Template

clip_image007

Put a Button in the template

clip_image009

Click on the Button then set the DataContext

clip_image011

….to the ViewModel that the main page is using.

clip_image013

Drop an Behavior on the Button.

clip_image015

You will then be able to raise any ICommand on the main ViewModel (otherwise the ICommands are “out of scope”)

clip_image017

However, your problem is now the button is using the “scope of the main page” you no longer have access to the row that you are currently on so you can’t pass it as a parameter.

No problem, the “contentPresenter” (the parent of the Button) is STILL bound to the “context of the current row” so you can simply pass it’s DataContext as a Parameter.

So, now the following ICommand will work:

        #region ClearCommand
        public ICommand ClearCommand { get; set; }
        public void Clear(object param)
        {
            // Clear the Comment
            RIAComment objRIAComment = (RIAComment)param;
            objRIAComment.Comment = "****";
        }
 
        private bool CanClear(object param)
        {
            // Do not allow if there is no Current RIAComment
            return (param as RIAComment != null);
        }
        #endregion

Download the code sample here:

http://silverlight.adefwebserver.com/files/RIADataGridButtonInADataGrid.zip





Comments are closed.