Donate

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:
<Window.Resources>  
      <src:BorderBrushConverter x:Key="BorderBrushConverter" />  
   </Window.Resources>    
XAML markup:
 <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> 
Converter class:
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();
        }
    }
Datagrid window:
Change WPF DataGridCell Background Color Using IValueConverter
Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.