![cover](https://img-blog.csdnimg.cn/direct/2025caad69b14148bd7a998926811ea7.png)
WPF中DataGrid动态生成列及自定义表头结构
DataGrid动态生成列并实现数据绑定,以及如何实现复杂的表头和列内容
目录
一、DataGrid动态生成列
通常情况下,DataGrid动态生成列通过绑定DataTable类型的数据源实现。此方法很适用于数据库单表查询并且表结构为横表形式,倘若数据结构存在嵌套或者表结构为竖表形式,则需要做很多工作进行处理。
以下从List<object>类型的行数据入手,来探究如何进行列的生成与数据绑定。object可以是基础数据类型,也可以是任意自定义的数据结构。
1、首先自定义一个数据结构如下:
public class Factor
{
public string Name { get; set; }
public string Min { get; set; }
public string Avg { get; set; }
public string Max { get; set; }
public string Flag { get; set; }
}
2、假设每行数据由DataTime和N个Factor组成,创建一个包含数据源的ViewModel如下:
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private List<List<object>> m_DataSource;
public List<List<object>> DataSource
{
get { return m_DataSource; }
set
{
if (m_DataSource != value)
{
m_DataSource = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DataSource)));
}
}
}
public MainViewModel()
{
//这里先创建临时变量,待数据填充完毕后赋值给DataSource,原因待会会说~
var dataSource = new List<List<object>>();
for (int i = 0; i < 5; i++)
{
var row = new List<object>();
row.Add(DateTime.Now.AddDays(i));
row.Add(new Factor { Name = "CO2", Min = "12.34" + i, Avg = "13.45" + i, Max = "14.56" + i, Flag = "N" });
row.Add(new Factor { Name = "NO2", Min = "23.14" + i, Avg = "25.25" + i, Max = "27.36" + i, Flag = "N" });
row.Add(new Factor { Name = "SO2", Min = "34.45" + i, Avg = "35.56" + i, Max = "36.67" + i, Flag = "N" });
dataSource.Add(row);
}
DataSource = dataSource;
}
}
3、主界面添加一个DataGrid,并绑定数据源到DataSource
<DataGrid x:Name="dataGrid" ItemsSource="{Binding DataSource}"/>
后台ViewModel绑定
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
4、此时通过监听DataGrid的ItemsSource,来创造动态绑定时机(也可以继承DataGrid,并重写OnItemsSourceChanged或OnItemsChanged方法来实现)
以下为监听ItemsSource并实现动态绑定的代码:
/// <summary>
/// 动态生成DataGrid的列
/// </summary>
private void AutoGenerateDataGridColumns()
{
var dpDescriptor = DependencyPropertyDescriptor.FromProperty(DataGrid.ItemsSourceProperty, typeof(DataGrid));
dpDescriptor.AddValueChanged(dataGrid, (s, e) =>
{
dataGrid.Columns.Clear();
if (dataGrid.ItemsSource is List<List<object>> dataSource && dataSource?.Count > 0)
{
var firstRow = dataSource.First();
for (int i = 0; i < firstRow.Count; i++)
{
if (firstRow[i] is Factor factor)
{
//待会实现
}
else
{
this.dataGrid.Columns.Add(new DataGridTextColumn()
{
Header = "时间",
IsReadOnly = true,
Binding = new Binding("[" + i.ToString() + "]")
{
StringFormat = "yyyy/MM/dd HH:mm:ss"
},
ElementStyle = (Style)this.FindResource("DataGridTextColumnStyle")
});
}
}
}
});
}
要点即是Column绑定到List的索引上
二、自定义Factor列样式
方才定义了Factor数据结构,是想在同一列中显示多个字段,并且表头与内容一一对齐。那么接下来要做两件事情:实现针对Factor列的DataGridColumnHeader和DataGridTemplateColumn样式
1、由于Factor列的表头内容是动态生成的,因此先定义一个针对Header的数据结构:
public class FactorColumnHeaderModel
{
public string Header { get; set; }
public List<string> SubHeaders { get; set; }
/// <summary>
/// 由于标记列可能不需要显示,所以单独用布尔类型绑定
/// </summary>
public bool HasFlag { get; set; } = true;
}
接着是重写的DataGridColumnHeader样式
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<Style x:Key="FactorColumnHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Grid HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.ColumnSpan="2" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding SubHeaders}" HorizontalContentAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding SubHeaders.Count}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding .}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Text="标记" Grid.Row="1" Grid.Column="1" Width="50" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding HasFlag,Converter={StaticResource BooleanToVisibilityConverter}}"/>
<Thumb x:Name="PART_RightHeaderGripper" Grid.RowSpan="2" Grid.ColumnSpan="2" Cursor="SizeWE" HorizontalAlignment="Right" Width="2" Background="Transparent">
<Thumb.Template>
<ControlTemplate TargetType="Thumb">
<Rectangle Fill="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
(说明:这里“标记”子列是固定列宽的,其他列均分剩余宽度)
2、实现针对Factor列的DataGridTemplateColumn,由于需要动态绑定数据源,因此必须通过代码生成DataGridTemplateColumn的CellTemplate.
这里有两种做法:一是通过FrameworkElementFactory一个个创建元素,这种做法代码过长,已被我Pass。故采用第二种做法,创建DataTemlate的Xaml代码段,利用XamlReader生成DataTemplate实例。
代码段生成函数如下:
/// <summary>
/// 生成DataTemlate的代码片段
/// </summary>
/// <param name="cellBindingList">每个元素对应的数据绑定字符串集合</param>
/// <param name="hasFlag">是否包含独立的标记列(对应表头)</param>
/// <returns></returns>
public static string GetCellTemplateXaml(List<string> cellBindingList, bool hasFlag)
{
var templateStr = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">";
templateStr += "<Grid><Grid.ColumnDefinitions><ColumnDefinition Width=\"*\" /><ColumnDefinition Width=\"Auto\" /></Grid.ColumnDefinitions>";
templateStr += $"<UniformGrid Columns=\"{(hasFlag ? cellBindingList.Count - 1 : cellBindingList.Count)}\">";
cellBindingList.ForEach(a =>
{
if (!hasFlag || a != cellBindingList.Last())
{
templateStr += "<TextBlock Margin=\"10 0 10 0\" Text=\"{Binding " + a + "}\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" />";
}
});
templateStr += "</UniformGrid>";
if (hasFlag)
{
templateStr += "<TextBlock Grid.Column=\"1\" Text=\"{Binding " + cellBindingList.Last() + "}\" Width=\"50\" TextAlignment=\"Center\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" />";
}
templateStr += "</Grid></DataTemplate>";
return templateStr;
}
最终动态生成列部分的代码如下:
/// <summary>
/// 动态生成DataGrid的列
/// </summary>
private void AutoGenerateDataGridColumns()
{
var dpDescriptor = DependencyPropertyDescriptor.FromProperty(DataGrid.ItemsSourceProperty, typeof(DataGrid));
dpDescriptor.AddValueChanged(dataGrid, (s, e) =>
{
dataGrid.Columns.Clear();
if (dataGrid.ItemsSource is List<List<object>> dataSource && dataSource?.Count > 0)
{
var columnHeaderStyle = this.FindResource("FactorColumnHeaderStyle") as Style;
var firstRow = dataSource.First();
for (int i = 0; i < firstRow.Count; i++)
{
if (firstRow[i] is Factor factor)
{
// 表头绑定的数据源
var factorHeaderSource = new FactorColumnHeaderModel()
{
HasFlag = true,
Header = factor.Name,
SubHeaders = new List<string>() { "最小值", "均值", "最大值" }
};
// 列中元素绑定的数据源
var bindingList = new List<string>();
bindingList.Add($"[{i}].Min");
bindingList.Add($"[{i}].Avg");
bindingList.Add($"[{i}].Max");
bindingList.Add($"[{i}].Flag");
var factorCellTemplateStr = GetCellTemplateXaml(bindingList, factorHeaderSource.HasFlag);
var templateColumn = new DataGridTemplateColumn()
{
Header = factorHeaderSource,
HeaderStyle = columnHeaderStyle,
CellTemplate = (DataTemplate)XamlReader.Parse(factorCellTemplateStr)
};
this.dataGrid.Columns.Add(templateColumn);
}
else
{
this.dataGrid.Columns.Add(new DataGridTextColumn()
{
Header = "时间",
IsReadOnly = true,
Binding = new Binding("[" + i.ToString() + "]")
{
StringFormat = "yyyy/MM/dd HH:mm:ss"
},
ElementStyle = (Style)this.FindResource("DataGridTextColumnStyle")
});
}
}
}
});
}
三、对DataGrid及相关元素进行样式调整
<Style x:Key="DataGridCellStyle" TargetType="DataGridCell">
<Setter Property="FontSize" Value="12"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Background" Value="Transparent" />
</Style>
<Style x:Key="DataGridRowStyle" TargetType="DataGridRow">
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style x:Key="DataGridColumnHeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0,0,1,1"/>
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
<Style x:Key="DataGridTextColumnStyle" TargetType="TextBlock">
<Setter Property="Margin" Value="10,0"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style TargetType="DataGrid">
<Setter Property="ColumnHeaderHeight" Value="45"/>
<Setter Property="RowHeight" Value="30"/>
<Setter Property="RowHeaderWidth" Value="0"/>
<Setter Property="AutoGenerateColumns" Value="False"/>
<Setter Property="Background" Value="#304050"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="HorizontalGridLinesBrush" Value="White"/>
<Setter Property="VerticalGridLinesBrush" Value="White"/>
<Setter Property="CanUserAddRows" Value="False"/>
<Setter Property="CellStyle" Value="{StaticResource DataGridCellStyle}"/>
<Setter Property="RowStyle" Value="{StaticResource DataGridRowStyle}"/>
<Setter Property="ColumnHeaderStyle" Value="{StaticResource DataGridColumnHeaderStyle}"/>
</Style>
最终实现效果如图:
![Logo](https://devpress.csdnimg.cn/79de2bf0b7994defa4242ef90d5513fa.jpg)
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)