将对象绑定到datagrid列

时间:2013-05-13 11:54:57

标签: c# wpf data-binding datagrid

我有一个employee类,其中包含person类的实例:

List<Employee> emp = (AdventureWorks.Employees.Select(n => n)).ToList();

showgrid.ItemsSource = emp;
showgrid.Columns.Clear();

DataGridTextColumn data_column = new DataGridTextColumn();
data_column.Binding = new Binding("Person=>FirstName");
data_column.Header = "First Name";

showgrid.Columns.Add(data_column);

如何将firstname对象中的字段person与列First Name绑定在一起?

2 个答案:

答案 0 :(得分:0)

如果您想在代码中执行此操作,您可以执行如下所示的操作:

    private void BindDataToGrid()
    {
        //Sample Data
        List<Employee> empList =new List<Employee>();        
        empList.Add(new Employee(){FirstName = "Rob", LastName="Cruise"});
        empList.Add(new Employee() { FirstName = "Lars", LastName = "Fisher" });
        empList.Add(new Employee() { FirstName = "Jon", LastName = "Arbuckle" });
        empList.Add(new Employee() { FirstName = "Peter", LastName = "Toole" });

        DataGridTextColumn data_column = new DataGridTextColumn();
        data_column.Binding = new Binding("FirstName");
        data_column.Header = "First Name";
        showgrid.Columns.Add(data_column);

        data_column = new DataGridTextColumn();
        data_column.Binding = new Binding("LastName");
        data_column.Header = "Last Name";

        showgrid.Columns.Add(data_column);
        showgrid.ItemsSource = empList;
        showgrid.AutoGenerateColumns = false;
    }

    private class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

答案 1 :(得分:0)

您的员工班级中的班级人员需要公共财产。例如

public person MyPerson {get;set;}

然后你可以用“。”绑定。在你的绑定

data_column.Binding = new Binding("MyPerson.FirstName");