2013-05-13 81 views
1

我有一个employee类,其中包含一个person类的一个实例:绑定的对象到DataGrid列

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绑定列First Nameperson对象里面?

+2

你为什么以编程方式创建你的绑定?当然,使用XAML可以更容易实现。 – 2013-05-13 11:57:47

+0

理想情况下,您应该在XAML中创建绑定而不是在代码中。实际上你的datagrid本身应该在XAML中定义。 – cvraman 2013-05-13 11:59:48

+0

请更仔细地选择您的标签 - 无需使用3个不同的C#标签 – stijn 2013-05-13 12:00:52

回答

0

你需要为你的类人的公共属性在你的员工类。例如。

public person MyPerson {get;set;} 

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

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

其已公开.....不工作与点 – 2013-05-13 13:28:53

+0

谢谢....这工作使用Linq – 2013-05-13 14:06:19

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

实际上名字和姓氏字段在类人员内部。员工拥有类型为人的财产。 – 2013-05-13 12:11:47