How to create Style for WPF DataGrid with Trigger

XAML WPF Developer 31 Reputation points

Hi To All,
How to create DataGrid Style in WPF/XAML with Trigger(Change Color Row Selected & Mousehover). Please find below attached image.



A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
789 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 47,331 Reputation points Microsoft Vendor

    For changing the color of the selected row and hovering with trigger, you could refer to the following code.
    The code of xaml:

            <DataGrid Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="False">  
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>  
                    <Style TargetType="DataGridRow" >  
                            <Trigger Property="IsMouseOver" Value="True">  
                                <Setter Property="Background" Value="Orange"/>  
                                <Setter Property="Foreground" Value="Purple"/>  
                                    <Condition Property="IsSelected" Value="true" />  
                                    <Condition Property="Selector.IsSelectionActive" Value="true" />  
                                <Setter Property="Foreground" Value="White" />  
                                <Setter Property="Background" Value="OrangeRed"/>  
                    <DataGridTextColumn Header="Name"  Binding="{Binding Name}"/>  
                    <DataGridTextColumn Header="EmployeeNumber"  Binding="{Binding EmployeeNumber}"/>  

    The code of xaml.cs:

    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Windows;  
    namespace StyleforDataGridwithTrigger  
      public partial class MainWindow : Window  
        private ObservableCollection<Employee> EmployeeInfoDataSource { get; set; }  
        public MainWindow()  
          DataContext = this;  
          dg.ItemsSource = EmployeeInfoDataSource;  
        private void Init()  
          EmployeeInfoDataSource = new ObservableCollection<Employee>();  
          for (int i = 0; i < 5; i++)  
            EmployeeInfoDataSource.Add(new Employee { Name = "name" + i, EmployeeNumber = i });  
        public event PropertyChangedEventHandler PropertyChanged;  
        protected void OnPropertyChanged(string propertyName)  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
      public class Employee  
        public string Name { get; set; }  
        public int EmployeeNumber { get; set; }  

    The picture of result:

    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.