How to change the background color of a WPF DataGrid widget to match the background color of a cell?

Background

I am using VS2010, a DataGrid (the one that comes with WPF), and I manually create rows and columns. I set different colors for the lines, depending on their state (but for simplicity we can say that it was yellow). It worked because the datagrid used shortcuts to display the text, and when I set the background for the row, it also appears as a widget.

However, I could not ctrl + c (copy) the contents of the cell, so now I create my own template for the columns, and I use a text box to display the data.

Problem

Texbox blocks the background of the cells, so in reality I get (for example) a datagrid with white cells (text fields) with yellow borders.

Question

How to make text fields (this is my case) know the background color of the cells? I tried to use the trick and set a transparent brush for all text fields, but I still get a white background in the cells (text fields).

Current code:

        grid.BeginInit();
        grid.Columns.Clear();


        int i = 0;

        var glass_brush = new SolidColorBrush(Color.FromArgb(255,0,0,0));

        foreach (var db_col in query.FieldNames)
        {
            var template = new DataTemplate();
            var elemFactory = new FrameworkElementFactory(typeof(TextBox));
            elemFactory.SetBinding(TextBox.TextProperty, new Binding(String.Format("Visual[{0}]", i)));
            // make the background transparent -- it does not work though
            elemFactory.SetValue(TextBlock.BackgroundProperty,glass_brush);
            template.VisualTree = elemFactory;

            var col = new DataGridTemplateColumn();
            col.CellTemplate = template;
            col.IsReadOnly = true;
            col.Header = db_col;
            grid.Columns.Add(col);
            ++i;
        }

        {
            grid.Items.Clear();


            foreach (var db_row in diffs)
            {
                var row = new DataGridRow();
                row.Item = db_row.Item1;
                row.Background = colors[db_row.Item2];
                grid.Items.Add(row);
            }
        }
        grid.IsReadOnly = true;

        grid.EndInit();
+3
source share
1 answer

You install TextBlock.BackgroundPropertythat is based on TextElement.BackgroundProperty, instead of installing TextBox.BackgroundPropertyor Control.BackgroundPropertythat is based on Panel.BackgroundProperty. In addition, yours glass_brushis an opaque black brush instead of a transparent one. You can use Brushes.Transparent. Try:

elemFactory.SetValue(Control.BackgroundProperty, Brushes.Transparent);
+4
source

Source: https://habr.com/ru/post/1761287/


All Articles