WPF中DataGrid如何动态生成列及自定义表头结构

WPF中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; }
            if (m_DataSource != value)
                m_DataSource = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DataSource)));
    public MainViewModel()
        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}" AutoGenerateColumns="False" ColumnHeaderHeight="30" RowHeight="30"/>

后台ViewModel绑定

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
    public MainWindow()
        InitializeComponent();
        this.DataContext = new MainViewModel();
}

4、此时通过监听DataGrid的ItemsSource,来创造动态绑定时机(也可以继承DataGrid,并重写OnItemsSourceChanged或OnItemsChanged方法来实现)

以下为监听ItemsSource并实现动态绑定的代码:

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)
                //待会实现
                this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "时间", Binding = new Binding("[" + i.ToString() + "]") { StringFormat = "yyyy/MM/dd HH:mm:ss"} });
});

要点即是Column要Binding到List的索引上


二、自定义表头结构

方才定义了Factor数据结构,是想在同一列中显示多个字段,并且表头一一对齐。那么接下来要做两件事情:1、重写DataGridColumnHeader样式;2、实现一个针对Factor列的DataGridTemplateColumn.

1、在重写DataGridColumnHeader样式的时候,我希望通过数据绑定来实现子列标题排版。于是先定义一个针对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"/>
                            </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;
}

最终动态生成列部分的代码如下:

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);