簡體   English   中英

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

[英]How to change WPF DataGrid cell widget background color according to cell background color?

背景

我使用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();

您將設置基於TextElement.BackgroundProperty TextBlock.BackgroundProperty ,而不是設置基於Panel.BackgroundProperty TextBox.BackgroundPropertyControl.BackgroundProperty 同樣,您的glass_brush是不透明的黑色畫筆,而不是透明的畫筆。 您可以使用Brushes.Transparent 嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM