WPF Datagrid CellFormatting 事件

WPF Datagrid CellFormatting event

这是我关于 Whosebug 的第一个问题,即使我已经使用它 2 年了。 (很有帮助)。很抱歉,如果没有正确询问。

我正在将一个项目从 WinForms 转移到 WPF,但遇到了一些麻烦。 我有一个数据网格,它会根据 SQL 请求自动填充,并且当单元格格式化时触发事件 'DataGridViewCellFormatting'。 我正在使用此事件使线条颜色不同。 (更加人性化)

WinForm 上的代码:

    private void ChangerCouleur(object sender, DataGridViewCellFormattingEventArgs e)
    {
        DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
        row.DefaultCellStyle.SelectionBackColor = Color.Orange;
        row.DefaultCellStyle.SelectionForeColor = Color.Black;
        if (e.RowIndex % 2 == 0)
        {
            row.DefaultCellStyle.BackColor = Color.Khaki;
            row.DefaultCellStyle.ForeColor = Color.Black;
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.Goldenrod;
            row.DefaultCellStyle.ForeColor = Color.Black;
        }
    }

我在 WPF 中找不到相同的事件。

提前致谢

查看您的代码示例,我认为您想要更改交替行的颜色?

如果是这样,您可以在 XAML stlye 中这样做:

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="Background" Value="#FFF" />
    <Setter Property="AlternationCount" Value="2" />
</Style>

 <Style TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Background" Value="Khaki"/>
            <Setter Property="Foreground" Value="Black"/>
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Background" Value="Goldenrod"/>
            <Setter Property="Foreground" Value="Black"/>
        </Trigger>
    </Style.Triggers>
</Style>

DataGridCell 连同每个 WPF 视觉项目都包含一个 Initialized event. For your purposes this may be what you are looking for. There is also the Loaded 事件,如果您需要在项目完成后与它交互 首次布局和渲染。

您可能会发现,仅使用 XAML 和 DataGrid.AlternatingRowBackground:

即可达到您想要的结果
<DataGrid RowBackground="Khaki" 
          AlternatingRowBackground="Goldenrod"
          Foreground="Black">
    <DataGrid.Resources>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Orange"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
</DataGrid>