Quent
Quent

Reputation: 81

WPF Datagrid CellFormatting event

This is my first question on stackoverflow even if I've been using it since 2 years. (Pretty helpful). So sorry if this is not asked properly.

I'm moving a project from WinForms to WPF, and I'm having some troubles. I have a datagrid that fills automatically on SQL request, and when the cells are formatting the event 'DataGridViewCellFormatting' is triggered. I'm using this event to make line color different. (more user-friendly)

Code on 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;
        }
    }

I can't find the same event in WPF.

Thanks in advance

Upvotes: 0

Views: 2133

Answers (2)

deloreyk
deloreyk

Reputation: 1239

The DataGridCell along with every WPF visual item contains a Initialized event. For your purposes this may be what you are looking for. There is also the Loaded event if you need to interact with your item after it has been laid out and rendered for the first time.

You may find that you can achieve your desired result by using purely XAML using 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>

Upvotes: 3

Glen Thomas
Glen Thomas

Reputation: 10764

Looking at your code sample, I think you want to change the colour of alternating rows?

If so, you can do it in a XAML stlye like this:

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

Upvotes: 1

Related Questions