Change DataGrid cell colour based on values

前端 未结 8 1708
栀梦
栀梦 2020-11-22 08:48

I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml

Style TargetType=\"DataGridCell\"

8条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:28

    Based on the answer by 'Cassio Borghi'. With this method, there is no need to change the XAML at all.

            DataGridTextColumn colNameStatus2 = new DataGridTextColumn();
            colNameStatus2.Header = "Status";
            colNameStatus2.MinWidth = 100;
            colNameStatus2.Binding = new Binding("Status");
            grdComputer_Servives.Columns.Add(colNameStatus2);
    
            Style style = new Style(typeof(TextBlock));
            Trigger running = new Trigger() { Property = TextBlock.TextProperty, Value = "Running" };
            Trigger stopped = new Trigger() { Property = TextBlock.TextProperty, Value = "Stopped" };
    
            stopped.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Blue });
            running.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Green });
    
            style.Triggers.Add(running);
            style.Triggers.Add(stopped);
    
            colNameStatus2.ElementStyle = style;
    
            foreach (var Service in computerResult)
            {
                var RowName = Service;  
                grdComputer_Servives.Items.Add(RowName);
            }
    

提交回复
热议问题