简体   繁体   中英

How to change WPF DataGrid cell widget background color according to cell background color?

The background

I use VS2010, DataGrid (the one delivered with WPF) and I manually create rows and columns. I set various colors for rows, depending of their state (but for simplicity let's say it was yellow). It worked because datagrid used labels for displaying text, and when I set background for row, it is reflected in label widget as well.

However, I couldn't ctrl+c (copy) content of the cell, so now I create custom template for columns and I use textbox to show the data.

The problem

Texbox blocks background of the cells, so in effect I get (for example) datagrid with white cells (textboxes) with yellow borders.

The question

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

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();

You are setting TextBlock.BackgroundProperty , which is based on TextElement.BackgroundProperty , instead of setting TextBox.BackgroundProperty or Control.BackgroundProperty , which is based on Panel.BackgroundProperty . Also, your glass_brush is an opaque black brush instead of a transparent one. You can use Brushes.Transparent . Try:

elemFactory.SetValue(Control.BackgroundProperty, Brushes.Transparent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM