WPF DataGrid columns表头根据数据集动态动态生成Demo

        思路是这样的,数组集合装表头的信息,遍历这个集合,遍历过程中处理一下数据,然后就把每表头信息添加到dataGrid2.Columns.Add(templateColumn);

1,页面Xaml代码:

  

2,声明一个类:

public class TY_DataGridColumsHeader
{
    public string Name { get; set; }

    public object HeaderTitle { get; set; }

    public object IsVisible { get; set; }
}

3,声明表头数据集合,再遍历。 

#region 自己创建的DataGrid表头
            var dpDescriptor2 = System.ComponentModel.DependencyPropertyDescriptor.FromProperty(DataGrid.ItemsSourceProperty, typeof(DataGrid));

            ObservableCollection listheadttile = new ObservableCollection();
            listheadttile.Add(new TY_DataGridColumsHeader()
            {
                HeaderTitle = "名称",
                Name = "Name"
            });
            listheadttile.Add(new TY_DataGridColumsHeader()
            {
                HeaderTitle = "年龄",
                Name = "Age"
            });

            dpDescriptor2.AddValueChanged(dataGrid2, (s, e) => {
                dataGrid2.Columns.Clear();

                foreach (var item in listheadttile)
                {
                    var templateColumn = new DataGridTemplateColumn()
                    {
                        Header = item.HeaderTitle,
                        CellTemplate = (DataTemplate)XamlReader.Parse(GetCellTemplateXaml2(item.Name))
                    };
                    dataGrid2.Columns.Add(templateColumn);
                }


            });

#endregion

4,cell的模版 

public static string GetCellTemplateXaml2(string listheadttile)
        {
            var templateStr = "";
            //templateStr += "";
            //templateStr += $"";
            //cellBindingList.ForEach(a =>
            //{
            //    if (!hasFlag || a != cellBindingList.Last())
            //    {
            //        templateStr += "";
            //    }
            //});
            //templateStr += "";
            //if (hasFlag)
            //{
            //    templateStr += "";
            //}
            templateStr += "";

            templateStr += "";

            templateStr += "";
            return templateStr;
        }

你可能感兴趣的:(WPF,wpf)