WPF自动产生列,前台代码:
<DataGrid x:Name="Dg" AutoGenerateColumns="True" CanUserAddRows="False"
AutoGeneratingColumn="Dg_OnAutoGeneratingColumn"
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<string> { "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;
}
效果图: