Search code examples
wpfwpfdatagrid

WPF Datagrid column foreground cannot be set


i want to set the foreground of the column in a wpf datagrid to green. I tried this way. But it is not working.

   <dg:DataGrid.Columns>
      <dg:DataGridTextColumn Header="Customer" Binding="{Binding CustomerName}" Foreground="{Binding FontColor, Mode=OneWay}" Width="300" "/>

And in the model class, i have specified like this.

   private Brush _fontcolor;
    public Brush FontColor
    {
        get
        {
            return _fontcolor;
        }
        set
        {
            _fontcolor = value;
            OnPropertyChanged("FontColor");
        }
    }

And in the viewmodel class where i am populating datas, i have mentioned like this.

NotifyItem ni = new NotifyItem();
ni.CustomerID = (int)dr["CustomerID"];
ni.FontColor = Brushes.Green;
NotifyCollections.Add(ni);

What is wrong here ? Why the foreground is not set to Green ? Is there any way to set or bind the foreground to a color without going to DataGridTemplateColumn ?? Besides, I have set the background styles for the selected row. Below is the xaml.

    <dg:DataGrid.Resources>
        <LinearGradientBrush x:Key="jj" EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF4D77F9" Offset="0"/>
                <GradientStop Color="#FF96B5FF" Offset="1"/>
            </LinearGradientBrush>
            <Style TargetType="{x:Type dg:DataGridCell}">
                <Style.Triggers>
                    <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
                        <Setter Property="Background" Value="{StaticResource jj}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </dg:DataGrid.Resources>

Solution

  • Is there any way to set or bind the foreground to a color without going to DataGridTemplateColumn ?

    Yes. Use an ElementStyle:

    <DataGridTextColumn Header="Customer" Binding="{Binding CustomerName}" Width="300">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="{Binding FontColor}" />
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>