Category / Section
How to use the conditional formatting in TableSummaryCell of WPF DataGrid (SfDataGrid)?
1 min read
WPF DataGrid (SfDataGrid) allows you to apply different styles for the top and bottom table summaries by using the SfDataGrid.TableSummaryCellStyle property. You can apply some conditional based styling for each summary columns using converter like below code example.
C#
public class StyleConverter : IValueConverter { GridTableSummaryCell gridtablesummarycell; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { gridtablesummarycell = value as GridTableSummaryCell; var data = gridtablesummarycell.DataContext as SummaryRecordEntry; if (gridtablesummarycell.ColumnBase.ColumnIndex == 1) { if ((int)data.SummaryValues[0].AggregateValues.ElementAt(0).Value > 0) return Brushes.Red; else return Brushes.Blue; } else if (gridtablesummarycell.ColumnBase.ColumnIndex == 2) { if ((int)data.SummaryValues[1].AggregateValues.ElementAt(0).Value > 0) return Brushes.Red; else return Brushes.Blue; } else if (gridtablesummarycell.ColumnBase.ColumnIndex == 5) { if ((int)data.SummaryValues[2].AggregateValues.ElementAt(0).Value > 0) return Brushes.Red; else return Brushes.Blue; } return Brushes.Black; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
XAML
<Window.Resources> <local:StyleConverter x:Key="converter1"/> <Style TargetType="syncfusion:GridTableSummaryCell" x:Key="Tablesumamrycell"> <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource converter1}}"/> </Style> </Window.Resources> <syncfusion:SfDataGrid x:Name="sfdatagrid" TableSummaryCellStyle="{StaticResource Tablesumamrycell}" LiveDataUpdateMode="AllowSummaryUpdate" ItemsSource="{Binding Path=Products}" >
Universal Windows will not support IValueConverter in styling, but you can achieve the above requirement using StyleSelector like the below code example.
C#
public class TableSummaryStyleSelector : StyleSelector { protected override Style SelectStyleCore(object item, DependencyObject container) { var data = (SummaryRecordEntry)item; if ((int)data.SummaryValues[0].AggregateValues.ElementAt(0).Value > 0) return App.Current.Resources["TableSummaryStyle1"] as Style; return App.Current.Resources["TableSummaryStyle2"] as Style; } }
XAML
<Page.Resources> <local:TableSummaryStyleSelector x:Key="style"/> </Page.Resources> <syncfusion:SfDataGrid x:Name="sfdatagrid" AutoGenerateColumns="True" TableSummaryCellStyleSelector="{StaticResource style}" LiveDataUpdateMode="AllowSummaryUpdate" ItemsSource="{Binding Path=Products}" >
The following screenshot displaying the TableSummaryCell Style.