简体   繁体   English

将对象绑定到datagrid列

[英]Binding an object to a datagrid column

I have an employee class which contains an instance of a person class: 我有一个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);

How do I bind the field firstname inside the person object with the column First Name ? 如何绑定字段firstname里面person与列对象First Name

If you want to do it in code you would do something like the one shown below : 如果要在代码中执行此操作,则可以执行以下所示的操作:

    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; }
    }

you need a public property for your class person in your employee class. 您需要为员工班级中的班级人员提供公共财产。 eg. 例如。

public person MyPerson {get;set;}

then you can bind with "." 那么您可以绑定“。” in your bindings 在你的绑定中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM