簡體   English   中英

更改WPF Datagrid中單個單元格的顏色

[英]Changing color of a single cell in WPF Datagrid

我有一個WPF Datagrid,具有可變的列數,並在運行時使用String [] []的2D數組填充。

String[] data = .....;

datagrid.ItemsSource = data;

我需要根據其值對單元格顏色進行排序。 但是這些值由用戶在執行期間定義。 我發現的有關更改單元格顏色的大多數示例都在XAML上使用了觸發器,並且該值在設計時是已知的。

所以我要像這樣更改單元格的背景:

DataGridCell cell = DataGridUtils.GetCell(datagrid, i, j);

cell.Background = new SolidColorBrush(Colors.DarkGreen);

和GetCell函數:

private DataGridCell GetCell(int rowIndex, int colIndex, DataGrid dg)
{
    DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
    DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
    DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(colIndex) as DataGridCell;

    return cell;
}

乍看起來似乎還可以,我可以看到帶有該值的單元格為綠色。 但是,如果我一直向下滾動數據網格,然后以綠色更改向上返回單元格,則執行另一個隨機單元格,而更多的單元格將變為綠色。 如果我不斷上下移動,則綠色的單元格會隨機變化。

我知道這聽起來很奇怪,但是在代碼中只有一個地方可以更改單元格的顏色,並且只需單擊一下按鈕即可。 我不知道滾動數據網格時怎么回事。

我在某處讀到了ItemContainerGenerator,這不是一個優雅的解決方案,應避免使用。 但這是我設法完成這項工作的唯一方法。

有沒有更好的方法來更改單元格的背景顏色? 我可以在不知道設計時的值的情況下使用觸發器執行此操作嗎? 如果是這樣,怎么辦?

DataGrid VirtualizationMode默認為Recycling ,這意味着它將重用生成的DataCell以提高性能。 它不必創建n次控件。

將此添加到您的DataGrid

VirtualizingStackPanel.VirtualizationMode="Standard"

請注意,這會影響您的性能,WPF會產生n次控制。

暫無
暫無

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

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