我正在尝试使用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++;
}
}
}
欢迎提出建议。预先感谢。
答案 0 :(得分:0)
使用DataTrigger会使事情变得更容易。您可以添加IsCustom属性 到ViewModel,然后在单元格DataTrigger中检查其值。 可以在逻辑端设置IsCustom属性(在本例中为for循环)
<DataGrid>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding MyViewModel.IsCustom}" Value="True">
<Setter Property="Background" Value="Red"/>
<DataTrigger Binding="{Binding MyViewModel.IsCustom}" Value="false">
<Setter Property="Background" Value="White"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>