Change WPF Datagrid Row Color

后端 未结 2 447
夕颜
夕颜 2021-01-18 01:29

I have a WPF datagrid that is filled with an ObserverableCollection.

Now I want to color the rows depending on the row content at the program start and if something

相关标签:
2条回答
  • 2021-01-18 01:57

    To change it through code instead of a trigger it could look something like below. You can access the data as an array and then compare it. In this example I am comparing the 4th column to see if it is greater than 0 and the 5th column to see if it is less than 0 otherwise just paint it the default color. The try/catch it there becuase some logic needs to be added to see if it is a valid row or not.....or you can just ignore the errors as below (not really good practice though) but should be usable as is.

        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            try
            {
                if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[3].ToString()) > 0)
                {
                    e.Row.Background = new SolidColorBrush(Colors.Green);
                }
                else if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[4].ToString()) < 0)
                {
                    e.Row.Background = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    e.Row.Background = new SolidColorBrush(Colors.WhiteSmoke);
                }
            }
            catch
            {
            } 
        }
    
    0 讨论(0)
  • 2021-01-18 02:07

    Use the RowStyle. You can use the Triggers to change the color conditionally, or just bind it to a Brush property on your items and change that property respectively.

    0 讨论(0)
提交回复
热议问题