Everest
Everest

Reputation: 580

Enabling/Disabling row in a datagrid(MVVM pattern)

There is a datagrid with n number of rows, the first column in the Grid is a CheckBox column, now i want to enable/Disable some of the Rows(so that user cannot check the checkbox) of datagrid depending on some values.o How is it possible using MVVM pattern.

Upvotes: 1

Views: 1784

Answers (2)

user302084
user302084

Reputation: 176

Using the LoadingRow event for each row you can update the controls in any cell you desire. For instance,

private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    MyDataObjectClass dataContext = (e.Row.DataContext as MyDataObjectClass);

    foreach (DataGridColumn col in from cols in MyDataGrid.Columns orderby cols.DisplayIndex select cols)
    {
        FrameworkElement fe = col.GetCellContent(e.Row);

        DataGridCell result = fe.Parent as DataGridCell;

        // as an example, find a template column w/o a sort member path
        if (col is DataGridTemplateColumn && col.SortMemberPath == null)
        {

            CheckBox button = VisualTreeExtensions.GetChildrenByType<CheckBox>(fe)[0];
            button.IsEnabled = true; // insert your data condition...                        
        }
    }
}

Upvotes: 1

slugster
slugster

Reputation: 49985

You are probably binding a list (IEnumerable) of data objects to your grid. To keep it nice and clean, what you need to do is wrap each of those data objects with another object, let's call it the RowViewModel. This RowViewModel can then hold extra properties, like a boolean which you can bind your checkbox's IsEnabled property to, that boolean can be calculated from the state of the data object, or even from the state of the parent view model should you pass a reference of it to the RowViewModel.

You can also extend this a little further and have row specific context menu items controlled by each RowViewModel, etc. Using the RowViewModel in this way ensures that you keep your data object nice and pure, you don't pollute it with stuff it doesn't need.

Upvotes: 2

Related Questions