WPF DataGrid DataTrigger

Kailash Chandra Behera | Wednesday, November 11, 2020

Introduction

We are using WPF Trigger to execute a specific action based on the condition in WPF Controls. For example, in the Datagrid cell, you can change the background color if the cell value meets specific conditions, here in this article we will see how to add WPF Trigger to WPF Datagrid at run time using C# code.

Getting Started

The following example adds 3 data trigger to the first column of WPF Datagrid.

 Style style = new Style();   
 style.TargetType = typeof(DataGridCell);  
   
 // First trigger   
 DataTrigger DT = new DataTrigger();   
    
 Binding DataTriggerBinding = new Binding( “bindingName1”);   
 DataTriggerBinding.Mode = BindingMode.Default;   
 DataTriggerBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;   
 DT.Binding = DataTriggerBinding;   
 DT.Value = “<=100”;   
    
 Setter DataTriggerSetter = new Setter();   
 DataTriggerSetter.Property = DataGridCell.BackgroundProperty;   
 DataTriggerSetter.Value = Brushes.Red;   
 DT.Setters.Add(DataTriggerSetter);  
    
 style.Triggers.Add(DT);   
   
 // Second Trigger  
    
 DataTrigger DT1 = new DataTrigger();   
    
 Binding DataTriggerBinding1 = new Binding(“bindingName2”);   
 DataTriggerBinding1.Mode = BindingMode.Default;   
 DataTriggerBinding1.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;   
 DT1.Binding = DataTriggerBinding;   
 DT1.Value = “<=200”;  
    
 Setter DataTriggerSetter1 = new Setter();   
 DataTriggerSetter1.Property = DataGridCell.BackgroundProperty;   
 DataTriggerSetter1.Value = Brushes.Black;   
 DT1.Setters.Add(DataTriggerSetter1);   
                       
 style.Triggers.Add(DT1);   
    
  // Third Trigger  
 DataTrigger DT2 = new DataTrigger();   
    
 Binding DataTriggerBinding2 = new Binding(“bindingName3”);   
 DataTriggerBinding2.Mode = BindingMode.Default;   
 DataTriggerBinding2.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;   
 DT2.Binding = DataTriggerBinding2;   
 DT2.Value = “<=100”;   
    
 Setter DataTriggerSetter2 = new Setter();   
 DataTriggerSetter2.Property = DataGridCell.BackgroundProperty;   
 DataTriggerSetter2.Value = Brushes.Red;   
 DT2.Setters.Add(DataTriggerSetter2);   
                       
 style.Triggers.Add(DT2);   
   
  DataGridTextColumn dataGridTextColumn=(DataGridTextColumn) dgvRate.Columns[0];  
  dataGridTextColumn.CellStyle = style;   

WPF DataGrid Trigger

In the preceding, if the DataGrid cell value is greater or equal to 100 then the cell background color is read and if <= 200 then Black or > 200 then Green. Now we will do the same thing using C# code. We will need a data trigger class from the System.Window.Data namespace.

Summary

I hope you have understood how to add DataTrigger to WPF Datagrid columns and you have anjoyed it a lot.

Thanks