根据最小值更改 DataGridRow 颜色

Change DataGridRow color according to min value

我制作了一个 UI,其中包含一个 Button 和一个 DataGrid。我在生成四个列表的代码中进行了一些计算,如下所示:

var L = new List<MyDataObject>();
for (int z = 0; z < list_Exp.Count; z++)
{
    var d = new MyDataObject();

    d.AmountNeed = Math.Ceiling((goalexp - currentexp) / (list_Exp[z]));
    d.TotalLose = d.AmountNeed * (list_Amount_MadeFrom_One[z] * list_BuyPrice_MadeFrom_One[z] + list_Amount_MadeFrom_Two[z] * list_BuyPrice_MadeFrom_Two[z]);
    d.TotalGain = d.AmountNeed * list_AmountMade[z] * list_SellPrice[z];
    d.TotalCost = d.TotalGain - d.TotalLose;

    L.Add(d);
}

获得列表后,我在特定列表中找到最小值:

int i = L.FindIndex(x => x.TotalCost == L.Min(y => y.TotalCost));

并将所有列表添加到 dataGrid:

dataGrid.ItemsSource = L;

现在,我一直在尝试将 Rows[i] 的颜色更改为绿色或任何其他颜色。我尝试过类似的东西:

grid.Columns["NameOfColumn"].DefaultCellStyle.ForeColor = Color.Gray;

dataGrid.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

没有任何效果。

谢谢。

例如,您可以定义一个 RowStyle 并处理 DataGridRow 容器的 Loaded 事件,如下所示:

<DataGrid x:Name="dataGrid">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <EventSetter Event="Loaded" Handler="RowLoaded" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

private void RowLoaded(object sender, RoutedEventArgs e)
{
    DataGridRow dgr = sender as DataGridRow;
    MyDataObject x = dgr.DataContext as MyDataObject;
    if (x.TotalCost == dataGrid.Items.OfType<MyDataObject>().Min(y => y.TotalCost))
        dgr.Background = Brushes.Green;
}

only problem is when i scroll down (i have many rows), it colors few rows instead of finding only 1 min and then i get an error: "NullReferenceEXception was unhandled"

您可以将 DataGridRow 容器的 Background 属性 绑定到当前 MyDataObject 和对象集合,然后使用 MultiValueConverter

<DataGrid x:Name="dataGrid" xmlns:local="clr-namespace:WpfApplication1">
    <DataGrid.Resources>
        <local:Converter x:Key="conv" />
    </DataGrid.Resources>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource conv}">
                        <Binding Path="." />
                        <Binding Path="ItemsSource" RelativeSource="{RelativeSource AncestorType=DataGrid}" />
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

namespace WpfApplication1
{
    public class Converter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            MyDataObject x = values[0] as MyDataObject;
            if(x != null)
            {
                IEnumerable<MyDataObject> collection = values[1] as IEnumerable<MyDataObject>;
                if(collection != null && x.TotalCost == collection.Min(y => y.TotalCost))
                    return System.Windows.Media.Brushes.Green;
            }

            return System.Windows.DependencyProperty.UnsetValue;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}