Search code examples
c#wpfdatagridwpfdatagrid

How to make a row bold in WPF DataGrid


I have a DataGrid containing four rows, and I would need to make the texts in the last row bold, in order to better separate them from the rows above.

I tried the methods available in the question How to change a single datagrid row FontWeights to Bold?, but I was unable to get it working.

This is the code that I tried; running it results in an error, as row is null.

Setter bold = new Setter(TextBlock.FontWeightProperty, FontWeights.Bold, null);
DataGridRow row = (DataGridRow)DG_PPC.ItemContainerGenerator.ContainerFromIndex(3);
Style newStyle = new Style(row.GetType());
newStyle.Setters.Add(bold);
row.Style = newStyle;

I would appreciate any help you can give me. Thank you!

XAML code:

<DataGrid x:Name="DG_PPC" HorizontalAlignment="Left" Height="115" Margin="661,-6,0,0"
HeadersVisibility="Column" VerticalAlignment="Top" Width="726.25"
Loaded="DataGrid_PPC_Loaded" RowHeaderWidth="0" AutoGenerateColumns="False"
CanUserSortColumns="False" CanUserReorderColumns="False" FontSize="12" IsReadOnly="True">

Solution

  • I found myself another way to do it, which is compatible with my code. Here's the solution, in case someone will be needing something similar.

    APP.XML:

    <Application.Resources>
      <local:FontWeightConverter x:Key="FontWeightConverter"/>
    </Application.Resources>
    

    XAML:

    <DataGrid.RowStyle>
      <Style TargetType="{x:Type DataGridRow}">
        <Setter Property="FontWeight" Value="{Binding RelativeSource={RelativeSource Self},
          Path=Item.XYZ, Converter={StaticResource FontWeightConverter}}"/>
      </Style>
    </DataGrid.RowStyle>
    

    Code:

    class FontWeightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string name = (string)value;
            if (name.Equals("Δ"))
                return FontWeights.Bold;
            else
                return FontWeights.Normal;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }