使用M-V-VM Light根据Silverlight 4中的业务规则标准标记DataGrid行

时间:2011-05-02 22:17:44

标签: silverlight mvvm datagrid mvvm-light mvvm-toolkit

如果包含该单元格的行符合给定规则(假设其文本的值必须为“Incomplete”),我编写了代码来更改DataGrid单元格的前景属性。通过在代码中捕获LoadingRow事件并在其中编写逻辑,我可以使这项工作相当容易,但我觉得这不是一个非常优雅的MVVM实现。这是代码:

// Sets the foreground color of th 5th cell to red if the text in the cell corresponds 
// to a value specified in the ViewModel.
private void dgProfile_LoadingRow(object sender, DataGridRowEventArgs e)
    {

        this.dgProfile.SelectedIndex = e.Row.GetIndex();
        DataGridColumn column = this.dgProfile.Columns[4];
        FrameworkElement fe = column.GetCellContent(e.Row);
        FrameworkElement result = GetParent(fe, typeof(DataGridCell));
        if (result != null)
        {
            DataGridCell cell = (DataGridCell)result;
            if (((TextBlock)cell.Content).Text == (this.DataContext as ProfileViewModel).strIncompleteActivityStatus) cell.Foreground = new SolidColorBrush(Colors.Red);
            else cell.Foreground = new SolidColorBrush(Colors.Black);
        }

    }
    private FrameworkElement GetParent(FrameworkElement child, Type targetType)
    {
        object parent = child.Parent;
        if (parent != null)
        {
            if (parent.GetType() == targetType)
            {
                return (FrameworkElement)parent;
            }
            else
            {
                return GetParent((FrameworkElement)parent, targetType);
            }
        }
        return null;
    }

有人可以告诉我是否有更好的方法使用MVVM Light工具包实现这一点,可能通过RelayCommand和一些聪明的数据绑定?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以定义模板列并将前景属性绑定到返回相应SolidColorBrush的值转换器。

例如:

<data:DataGrid.Columns>
     <data:DataGridTemplateColumn>
                <data:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding MyProperty}"
                                   Foreground="{Binding MyProperty, Converter={StaticResource MyConverter}}"/>

                    </DataTemplate>
                </data:DataGridTemplateColumn.CellTemplate>
            </data:DataGridTemplateColumn>
</data:DataGrid.Columns>

转换器:

public class MyConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            string propertyValue = (string)value;

            if (propertyValue == strIncompleteActivityStatus)
                return new SolidColorBrush(Colors.Red);
            else
                return new SolidColorBrush(Colors.Black);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

此处有更多详情:

DataGrid cell color based on cell value