Change WPF DataGridCell Background Color Using IValueConverter
Here's a solution in painting a specific DataGridCell using IValueConverter. The datagrid set's it's ItemSource property either using List object or Datatable object.
Resource markup:
XAML markup:
Converter class:
Datagrid window:
Cheers!
Resource markup:
<Window.Resources>
<src:BorderBrushConverter x:Key="BorderBrushConverter" />
</Window.Resources>
<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" Grid.Row="2" Grid.Column="0" Name="dgStudents1"> <DataGrid.Columns> <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" /> <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True"> <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="Background" Value="{Binding Path=Age, Converter={StaticResource BorderBrushConverter}, ConverterParameter = 30, UpdateSourceTrigger=PropertyChanged}" /> </Style> </DataGridTextColumn.CellStyle> </DataGridTextColumn> <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" /> <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" /> </DataGrid.Columns> </DataGrid>
public class BorderBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture) { if (Int32.Parse(value.ToString()) >= (System.Convert.ToInt32(parameter))) return new SolidColorBrush(Colors.Gray); else return new SolidColorBrush(Colors.Transparent); } public object ConvertBack(object value, Type targetType, object parameter, System.GlobalizationCultureInfo culture) { throw new SystemNotImplementedException(); } }
Cheers!
Comments
Post a Comment