i'm using a Datagrid in WPF to populate some data. Once i have the data ready for display, i also need the first row, and only the first row to be bold. How can i achieve this?
Preferably i only want to modify my XAML. Worst case, i can make code changes on view-model (MVVM) side. But under no circumstance i am allowed to change the code-behind (ie: the view, so i cant give my DataGrid a x:Name and modify it from the view)
Please note datagrid may or may NOT be populated, so it cannot stop working if we attempt to bold a row that doesn't exist.
Thanks so much. Joe
A simple solution would be to implement a IMultiValueConverter
which checks the row index. You would use the DataGrid.CellStyle
to apply the converter:
CellFontWeightMultiValueConverter.cs
class CellFontWeightMultiValueConverter : IMultiValueConverter
{
#region Implementation of IMultiValueConverter
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) =>
values[0] is MyDataModel item
&& values[1] is IEnumerable<MyDataModel> items
&& items.ToList().IndexOf(item) == 0
? FontWeights.ExtraBold
: FontWeights.Normal;
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
#endregion
}
MainWindow.xaml
<Window>
<DataGrid ItemsSource="{Binding MyDataModels}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="FontWeight">
<Setter.Value>
<MultiBinding Converter="{StaticResource CellForegroundMultiValueConverter}">
<Binding />
<Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"
Path="DataContext.MyDataModels" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
</DataGrid>
</Window>