WPF AutoGeneratingColumn 绑定下拉框

WPF自动产生列,前台代码: 

 DataGrid绑定DataTable

private void TestPage_Loaded(object sender, RoutedEventArgs e)
        {
            var dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            dt.Columns.Add("gender");
            dt.Columns.Add("xAge");

            DataRow newRow = dt.NewRow();
            newRow["ID"] = "ID";
            newRow["Name"] = "Name";
            newRow["gender"] = "gender";
            newRow["xAge"] = "xAge";
            dt.Rows.Add(newRow);

            Dg.ItemsSource = dt.DefaultView;
        }

 因为数据源不固定(列名、列个数都不固定),所以必须自动生成列,并为每一列绑定下拉框;

下拉框的默认选中项为列的标题。实现字段映射功能

private void Dg_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var sexType = new List { "Age", "gender", "ID", "Name","Country" };
            var column = new DataGridTemplateColumn { Header = e.PropertyName };
            var dataTemplate = new DataTemplate();
            var fef = new FrameworkElementFactory(typeof(ComboBox));
            var binding = new Binding { Source = sexType };
            fef.SetBinding(ItemsControl.ItemsSourceProperty, binding);
            var selectVal = new Binding(e.PropertyName);//根据列名设置默认值
            fef.SetBinding(Selector.SelectedValueProperty, selectVal);
            dataTemplate.VisualTree = fef;
            column.CellTemplate = dataTemplate;
            e.Column = column;
            e.Column.Width = 100;
        }

 效果图:
WPF AutoGeneratingColumn 绑定下拉框_第1张图片

转载于:https://www.cnblogs.com/wondaz/p/3530434.html

你可能感兴趣的:(WPF AutoGeneratingColumn 绑定下拉框)