如果你记录了行号列号去改变单元格的颜色在滚动的时候就会颜色错位,这是因为在滚动的时候datagrid的列号会变
但是itemsource绑定的集合却不会变,我们可以用哪个集合去取得需要变色的单元格
方法是: var ad = targetDataGrid.Columns[col].GetCellContent(item) as TextBlock;,开始不晓得.GetCellContent还有这个重载
好了现在在datagrid的load_row 事件里加上这个方法就行了
try
{
int listkvsindex = 0;
foreach (var item in listkvs)//row
{
for (int col = 0; col < item.GetType().GetProperties().Count(); col++)
{
var ad = targetDataGrid.Columns[col].GetCellContent(item) as TextBlock;
if (ad != null)
{
KeyValuePair<int, int> m = new KeyValuePair<int, int>(listkvsindex, col);
if (UHService.needtored.Contains(m))
ad.Foreground = new SolidColorBrush(Colors.Red);
else
ad.Foreground = new SolidColorBrush(Colors.Black);
}
}
listkvsindex++;
}
}
catch { }
当然我这个datagrid是动态生成,直接用的原生的会有这个问题,如果后台用动态生成模板就不会有问题了
拼接的方式也是原生的效果,只是不晓得为什么很很卡
internal static DataGridTemplateColumn GetGridViewColumn(string header, string content, string color)
{
DataGridTemplateColumn tempCol = new DataGridTemplateColumn();
tempCol.Header = header;
tempCol.Width = new DataGridLength(80);
StringBuilder cellTemp = new StringBuilder();
cellTemp.Append("<DataTemplate ");
cellTemp.Append(" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'");
cellTemp.Append(" xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'");
cellTemp.Append(" xmlns:grid='clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.GridView'>");
cellTemp.AppendFormat(" <TextBlock Text=\"{{Binding {0}}}\" Foreground=\"{{Binding {1}}}\"></TextBlock>", content, color);
cellTemp.Append("</DataTemplate>");
tempCol.CellTemplate = (DataTemplate)XamlReader.Load(cellTemp.ToString());
StringBuilder cellTemp2 = new StringBuilder();
cellTemp2.Append("<DataTemplate ");
cellTemp2.Append(" xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'");
cellTemp2.Append(" xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'");
cellTemp2.Append(" xmlns:grid='clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.GridView'>");
cellTemp2.AppendFormat(" <TextBox Text=\"{{Binding {0}, Mode=TwoWay}}\"></TextBox>", content);
cellTemp2.Append("</DataTemplate>");
tempCol.CellEditingTemplate = (DataTemplate)XamlReader.Load(cellTemp2.ToString());
return tempCol;
}
/// <summary>
/// 为datagrid增加一列
/// </summary>
/// <param name="columname"></param>
/// <param name="columnBindName"></param>
public void AddColumn(string columname, string columnBindName,string col)
{
//DataGridTextColumn textColumn = new DataGridTextColumn();//textbox
//textColumn.Header = columname;
//textColumn.HeaderStyle = Application.Current.Resources["MyDaGTextCStyle"] as Style;
//textColumn.CellStyle = Application.Current.Resources["MyCellStyle"] as Style;
//textColumn.Width = new DataGridLength(80);
//textColumn.IsReadOnly = false;//列的格格可以直接输入
//textColumn.Binding = new Binding(columnBindName);
targetDataGrid.Columns.Add(GetGridViewColumn(columname, columnBindName,col));
}
这个问题纠结呀,