如何在 DataGrid 的最后一行设置背景颜色?

How to set the background color on the last row in a DataGrid?

我正在构建一个自定义控件,并希望添加一个可以设置 DataGrid 上最后一行背景颜色的功能。

我的第一个问题是如何 Select DataGrid 的最后一行。

第二个问题是如何为整行设置背景颜色。

可设置LastRowColor的自定义控件参考以下代码。我使用 LoadingRow 事件来设置最后一行的颜色。

class DatagridEx : DataGrid
{
    private static readonly DependencyProperty LastRowColourProperty = DependencyProperty.Register(nameof(LastRowColour), typeof(Brush), typeof(DatagridEx), new PropertyMetadata());

    public Brush LastRowColour
    {
        get => (Brush)GetValue(LastRowColourProperty);
        set => SetValue(LastRowColourProperty, value);
    }

    protected override void OnLoadingRow(DataGridRowEventArgs e)
    {
        base.OnLoadingRow(e);

        var index = Items.IndexOf(e.Row.DataContext);
        if (index == Items.Count - 1)
        {
            e.Row.Background = LastRowColour;
        }
    }
}

在 xaml 代码中使用它,如下所示:

<local:DatagridEx x:Name="dgr" LastRowColour="Red">
    ...        
</local:DatagridEx>