2013-05-13 82 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