WPF数据网格单元格格式事件

erhoui1w  于 2022-11-30  发布在  其他
关注(0)|答案(2)|浏览(158)

这是我关于stackoverflow的第一个问题,即使我已经用了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中找不到相同的活动。
先谢了

wbgh16ku

wbgh16ku1#

DataGridCell与每个WPF可视项目都包含一个Initialized事件。对于您的用途,这可能就是您要查找的内容。如果您需要在项目首次布局和呈现后与之交互,也可以使用Loaded事件。
您可能会发现,通过使用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>
qoefvg9y

qoefvg9y2#

看你的代码示例,我想你想改变交替行的颜色?
如果是这样,可以使用如下所示的XAML样式:

<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>

相关问题