启用/禁用数据网格中的行(MVVM模式)

时间:2011-10-16 11:07:00

标签: silverlight mvvm

有一个包含n行的数据网格,Grid中的第一列是CheckBox列,现在我想根据某些值启用/禁用datagrid的某些行(以便用户无法选中复选框) .o如何使用MVVM模式。

2 个答案:

答案 0 :(得分:2)

您可能正在将数据对象的列表(IEnumerable)绑定到网格。为了保持它的美观和干净,你需要做的是用另一个对象包装每个数据对象,让我们称之为 RowViewModel 。然后,此RowViewModel可以包含额外的属性,例如可以将复选框的IsEnabled属性绑定到的布尔值,可以从数据对象的状态计算布尔值,或者如果您传递参考,则可以从父视图模型的状态计算它到RowViewModel。

您还可以进一步扩展它,并使每个RowViewModel控制行特定的上下文菜单项等。以这种方式使用RowViewModel可确保您保持数据对象的美观和纯净,不会污染它的东西它不需要。

答案 1 :(得分:1)

对每行使用LoadingRow事件,您可以更新所需的任何单元格中的控件。例如,

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...                        
        }
    }
}