如何根据单元格背景色更改WPF DataGrid单元格小部件背景色?

gre*_*man 4 c# wpf datagrid templates

背景

我使用VS2010,DataGrid(WPF附带的那个),并手动创建行和列。根据行的状态,我为行设置了各种颜色(但为简单起见,假设它是黄色)。之所以起作用,是因为datagrid使用标签来显示文本,并且当我为行设置背景时,它也反映在标签小部件中。

但是,我无法ctrl + c(复制)单元格的内容,因此现在我为列创建自定义模板,并使用文本框显示数据。

问题

Texbox会阻止单元格的背景,所以实际上,我得到了(例如)带有带有黄色边框的白色单元格(文本框)的数据网格。

问题

如何使文本框(我的情况)知道单元格的背景色?我尝试使用技巧并为所有文本框设置透明笔刷,但是单元格(文本框)中仍然出现白色背景。

当前代码:

        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();
Run Code Online (Sandbox Code Playgroud)

Qua*_*ter 5

您正在设置TextBlock.BackgroundProperty,这是基于TextElement.BackgroundProperty,而不是设置TextBox.BackgroundProperty或者Control.BackgroundProperty,它是基于Panel.BackgroundProperty。另外,您glass_brush是不透明的黑色画笔,而不是透明的黑色画笔。您可以使用Brushes.Transparent。尝试:

elemFactory.SetValue(Control.BackgroundProperty, Brushes.Transparent);
Run Code Online (Sandbox Code Playgroud)