我已经编写了代码,如果包含该单元格的行满足给定规则(假设其文本必须具有值"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光工具包,也许通过RelayCommand和一些聪明的数据绑定?
提前感谢您的帮助!
您可以定义一个模板列,并将前景属性绑定到返回适当的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();
}
}
更多细节在这里:
基于单元格值的数据网格单元格颜色