WPF Foreground Color in a DataGrid, Change via Code (C#)?

Bernd Riemke 41 Reputation points
2020-06-28T15:13:24.553+00:00

Hi,
I need to Change a Foreground Color in a DataGrid Line, here ist the XAML Code from the Line in the DataGrid:

                   <DataGridTemplateColumn Header="Nr " Width="38" CanUserSort="True" x:Name="SP001" >
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Label x:Name="SP001F" Height="50" Content="{Binding GrLaufendePosition}" Foreground="Black" Background="White" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderThickness="0" VerticalAlignment="Center"  />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

SP001.Foreground = "Red"; is wrong :-(
SP001F.Foreground = "Red"; is wrong too :-(

Have anyone a idea?

Best Regards

Bernd

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,691 questions
0 comments No comments
{count} votes

Accepted answer
  1. gekka 7,486 Reputation points MVP
    2020-06-28T22:05:07.79+00:00

    There are many ways to do this, but the easier way is to refer with DynamicResource.

    <DataGrid x:Name="dataGrid1" >
        <DataGrid.Resources>
            <SolidColorBrush Color="Black" x:Key="columnForeground"/>
        </DataGrid.Resources>
    
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Nr " Width="38" CanUserSort="True" x:Name="SP001" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate >
                        <Label x:Name="SP001F" 
                        Height="50" 
                        Content="{Binding GrLaufendePosition}"
    
                        Foreground="{DynamicResource columnForeground}" 
    
                        Background="White" 
                        HorizontalAlignment="Center" 
                        HorizontalContentAlignment="Center" 
                        VerticalContentAlignment="Center" 
                        BorderThickness="0" 
                        VerticalAlignment="Center"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    
    
    this.dataGrid1.Resources["columnForeground"] = Brushes.Red;
    
    2 people found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Bernd Riemke 41 Reputation points
    2020-06-29T14:29:57.623+00:00

    I found what i Need :-)

    dg.RowBackground = Brushes.Red;

    :-)))

    0 comments No comments