Avalonia UI C# XAML WPF - 根据列值调整数据网格行颜色

Avalonia UI C# XAML WPF - Adjust data grid row color based on column value

public class EventLogView : UserControl
{
    private DataGrid dataGrid;
    public EventLogView()
    {
        this.InitializeComponent();
        dataGrid = this.FindControl<DataGrid>("EventLogsDataGrid");
        this.dataGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRows);
    } 

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    void dataGrid_LoadingRows(object sender, DataGridRowEventArgs e)
    {

    }
}

如果第 4 列的值为 "HIGH",我想将每一行的颜色更改为红色。

在 "pure" WPF 中执行此操作的方法是定义 ItemContainerStyleDataTrigger:

<DataGrid x:Name="EventLogsDataGrid"
                  AutoGenerateColumns="False"
                  Items="{Binding LogsData}"
                  CanUserReorderColumns="True"
                  CanUserResizeColumns="True"
                  IsReadOnly="True">
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Importance}" Value="HIGH">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.ItemContainerStyle>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Id}"
                                Header="ID"
                                Width="Auto"/>
        <DataGridTextColumn Binding="{Binding Content}"
                                Header="Content"
                                Width="Auto"/>
        <DataGridTextColumn Binding="{Binding CreationDate}"
                                Header="Date Time"
                                Width="Auto"/>
        <DataGridTextColumn Binding="{Binding Source}"
                                Header="Source"
                                Width="Auto"/>
        <DataGridTextColumn Binding="{Binding Importance}"
                                Header="Priority"
                                Width="Auto"/>
    </DataGrid.Columns>
</DataGrid>

但由于 Avalonia 不支持触​​发器,您可能必须像这样处理 LoadingRow 事件才能以编程方式设置 Background 属性:

void dataGrid_LoadingRows(object sender, DataGridRowEventArgs e)
{
    var dataObject = e.Row.DataContext as YourDataObject;
    if (dataObject != null && dataObject.Importance == "HIGH")
        e.Row.Background = Brushes.Red;
}