这两天逛CSDN 看到有个题主的需求 标题是 “c# wpf中datagrid中指定单元格背景色设置问题 ” 顺手解决了下 感觉挺有意思的就做下记录
想要实现的效果图 如下
大致需求我总结了下
1.属性值为"*"的单元格需要填充为指定背景色
2.数据源可能会有多种 即标题和字段数量都不固定
解决思路:
1.实现单元格按条件着色 这个倒是挺简单 一个CellTemplate 可以轻松解决
2.动态生成表格,不同数据源意味值 标题列名称都不固定无法前端固定,所以选择后台代码中动态生成模板。
3.在加载数据源之前先清理掉上一次的字段列,然后按数据源生成新的字段模板添加到datagrid中。
逻辑很简单 难点在于会不会写生成这个模板列这一步代码 (很多时候百度是有对应答案的)
实现代码如下
#用户登录可见
public class ManPeople
{
public string Name { get; set; }
public string Sex { get; set; }
public string Age { get; set; }
public string Address { get; set; }
public string Height { get; set; }
}
DataGrid TestDataGrid = new DataGrid() { AutoGenerateColumns = false };
public MainWindow()
{
InitializeComponent();
List peoples = new List();
peoples.Add(new ManPeople { Name = "*", Age = "18", Sex = "男" });
peoples.Add(new ManPeople { Name = "小王", Age = "*", Sex = "男" });
peoples.Add(new ManPeople { Name = "小龙", Age = "18", Sex = "*" });
peoples.Add(new ManPeople { Name = "小李", Age = "18", Sex = "男", Address = "*" });
peoples.Add(new ManPeople { Name = "小宋", Age = "18", Sex = "男", Address = "6666666", Height = "*" });
TestDataGrid.Columns.Clear();
AddTemplateColumn("姓名","Name");
AddTemplateColumn("年龄","Age");
AddTemplateColumn("性别","Sex");
AddTemplateColumn("地址", "Address");
AddTemplateColumn("身高", "Height");
this.TestDataGrid.ItemsSource = peoples;
this.Content = TestDataGrid;
}
void AddTemplateColumn(string Title,string BindName) {
var grid = new FrameworkElementFactory(typeof(Grid));
grid.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
var textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Stretch);
textBlock.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
textBlock.SetBinding(TextBlock.TextProperty, new Binding(BindName));
textBlock.AddHandler(TextBlock.LoadedEvent, new RoutedEventHandler(TextBlock_Loaded));
grid.AppendChild(textBlock);
var dataTemplate = new DataTemplate
{
VisualTree = grid
};
var templateColumn = new DataGridTemplateColumn
{
CellTemplate = dataTemplate,
Header = Title
};
TestDataGrid.Columns.Add(templateColumn);
}
private void TextBlock_Loaded(object sender, RoutedEventArgs e)
{
TextBlock tb = (TextBlock)sender;
if (tb.Text == "*")
{
tb.Background = Brushes.Red;
}
}
实现效果: