首页 > 其他 > 详细

WPF AutoGeneratingColumn 绑定下拉框

时间:2014-01-23 06:20:51      阅读:631      评论:0      收藏:0      [点我收藏+]

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

1
2
<DataGrid x:Name="Dg" AutoGenerateColumns="True" CanUserAddRows="False"
                      AutoGeneratingColumn="Dg_OnAutoGeneratingColumn"

 DataGrid绑定DataTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
        }

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
        }

 效果图:
bubuko.com,布布扣

WPF AutoGeneratingColumn 绑定下拉框

原文:http://www.cnblogs.com/wondaz/p/3530434.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!