Peter
Peter

Reputation: 11890

WPF datagrid - custom colors for each cell

In my application, I build all the rows and columns for a DataGrid programmatically. I would now like to control different UI aspects such as color, font, font size, borders, etc. programmatically for each cell. I am wondering if there is any on-cell-paint event that I can add a callback to and set all the aspects on per-cell basis. An example would be greatly appreciated.

Thank you in advance for your help.

Upvotes: 1

Views: 457

Answers (2)

Peter
Peter

Reputation: 11890

The best solution I found was to capture OnLoadingRow() of DataGrid. The following link shows a working example:

How to set background of a datagrid cell during AutoGeneratingColumn event depending on its value?

Upvotes: 1

javi
javi

Reputation: 159

I think there is not. I had the same problem as you and my solution was to create my own custom column and override the GenerateElement. I'll show you the code i can:

<cdgc:ColorTextColumn Binding="{Binding value}"

And then:

protected override System.Windows.FrameworkElement GenerateElement(System.Windows.Controls.DataGridCell cell, object dataItem)
    {
        var text = new TextBlock();
        text.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
        text.SetBinding(TextBlock.TextProperty, this.CopyBinding(this.DataBinding, null, null, null));

        text.Foreground = (System.Windows.Media.Brush).....;

        return text;
    }

As you can see I set the binding previously and maintained in the cell generation

Upvotes: 0

Related Questions