如何在 WPF DataGrid 中使行加粗

How to make a row bold in WPF DataGrid

我有一个包含四行的 DataGrid,我需要将最后一行中的文本加粗,以便更好地将它们与上面的行分开。

我尝试了问题 中提供的方法,但无法正常工作。

这是我试过的代码; 运行 它会导致错误,因为 row 为空。

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;

如果您能给我任何帮助,我将不胜感激。谢谢!

XAML代码:

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

我找到了另一种方法,它与我的代码兼容。这是解决方案,以防有人需要类似的东西。

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>

代码:

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();
    }
}