如何在WPF的gridview中设置列的背景颜色

问题描述:

我的gridview是从SQL中读取的Datatable动态生成的,现在我想设置一个特定的列,比如说,salary有一个红色的背景颜色。我搜索过许多解决方案,但仍然没有线索。

My gridview is dynamically generated from a Datatable read from SQL, now I want to set a particular column, say, "salary" to have a red background color. I've searched SO for many solutions but still have no clues.

CmdString = @"  select id, firstname, lastname, title, level, salary from emplpyees";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            dt = new DataTable("employee");
            sda.Fill(dt);
            datagridall.ItemsSource = dt.DefaultView;


您可以创建一个转换器类

You could create a converter class

public class ErrorConverters : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      SolidColorBrush myBrush = default(SolidColorBrush);

      if ((bool)value == true)
      {
        myBrush = new SolidColorBrush(Colors.Red);
      }
      else
      {
        myBrush = new SolidColorBrush(Colors.Black);
      }

      return myBrush;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      //Throw New NotImplementedException()
      return null;
    }
  }

然后使用行模板将背颜色绑定到任何您的数据库中的项目将被传递到转换器。

Then using a row template bind the back color to whatever item in your database would be passed to the converter.