【发布时间】:2018-12-28 10:57:31
【问题描述】:
我正在尝试在运行时使用 Column 和 Row 索引值更改 Datagrid (lst_DataFromDB) 中单个单元格的样式(设置背景)。
我创建了一个带有 2 个输入参数(rowNumber 和 colNumber)的函数。但是我在定位单个单元格时遇到了困难,该样式适用于整个列或所有行。
以下是我目前的进展-
private void getCellData(int rowNumber, int colNumber)
{
for (int i = 0; i < lst_DataFromDB.Items.Count; i++)
{
int j = 0;
foreach (DataGridColumn column in lst_DataFromDB.Columns)
{
if (rowNumber == i & colNumber == j)
{
DataGridRow row = (DataGridRow)lst_DataFromDB.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = column.GetCellContent(row) as TextBlock;
string texter = (cellContent.Text); //<--I'm able to fetch the cell text here, so I am targeting the required cell.
//METHOD 1:
StringReader stringReader = new StringReader("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" TargetType=\"{x:Type DataGridCell}\"> <Setter Property=\"Background\" Value=\"Red\"></Setter></Style>");
XmlReader xmlReader = XmlReader.Create(stringReader);
Style style = (Style)System.Windows.Markup.XamlReader.Load(xmlReader);
lst_DataFromDB.Columns[j].CellStyle = style; //<-- But, this highlights the entire Column
lst_DataFromDB.RowBackground = Brushes.YellowGreen; //<-- But, this highlights all the rows in the grid
//METHOD 2:
//***Throws an Error***
//column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty,Colors.Red));
//METHOD 3:
//***Throws an Error***
//((System.Windows.Controls.DataGridBoundColumn)column).ElementStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Colors.Red));
}
j++;
}
}
}
欢迎提出建议。提前致谢。
【问题讨论】:
-
你有没有想过
CellTemplateSelector? -
您可以查看用于设置 one 单元格样式的 XAML 解决方案。如果需要,您可以在后面的代码中进行此操作。 Link
标签: css .net wpf datagrid wpfdatagrid