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