2013-08-22 72 views
1

我想在數據網格中顯示員工列表數據。當我運行下面的代碼時,會顯示空白網格。將員工列表綁定到DataGrid

XAML

<Window x:Class="SampleWpfApplication1.DataGridBindToEmployeeList" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="DataGridBindToEmployeeList" Height="300" Width="300" 
     xmlns:local="clr-namespace:SampleWpfApplication1.ViewModel"> 
    <Window.Resources> 
     <local:EmployeeInfo x:Key="employeeInfo"/> 
    </Window.Resources> 
    <DataGrid ItemsSource="{Binding Source={StaticResource employeeInfo}}" AutoGenerateColumns="False" Height="300" Width="300" > 
     <DataGridTextColumn Binding="{Binding Path=EmployeeId}" Header="Employee Id" Width="300"/> 
     <DataGridTextColumn Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="300"/> 
    </DataGrid> 
</Window> 

的DataContext:

public class Employee 
    { 
     public int EmployeeId { get; set; } 
     public string EmployeeName { get; set; } 
    } 

    public class EmployeeInfo 
    { 
     public ObservableCollection<Employee> EmployeeList { get; set; } 

     public EmployeeInfo() 
     { 
      EmployeeList = new ObservableCollection<Employee>(); 

      for (int i = 0; i < 3; ++i) 
      { 
       EmployeeList.Add(new Employee() { EmployeeId = i, EmployeeName = i.ToString() + "ABC" }); 
      } 
     } 
    } 

輸出應爲:

Employee Id | Employee Name 
1    | 1ABC 
2    | 2ABC 
3    | 3ABC 

回答

0

試試這個:

<DataGrid ItemsSource="{Binding Source={StaticResource employeeInfo}, Path=EmployeeList}" AutoGenerateColumns="False" Height="300" Width="300" > 
    <DataGrid.Columns> 
     <DataGridTextColumn Binding="{Binding Path=EmployeeId}" Header="Employee Id" Width="300"/> 
     <DataGridTextColumn Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="300"/> 
    </DataGrid.Columns> 
</DataGrid> 

在您設置ItemsSource到整個EmloyeeInfo類的那一刻,你想指向您ObservableCollection<Employee>,還你忘了你的包裹列DataGrid.Columns

+0

代碼添加路徑後拋出異常「操作是無效的,同時的ItemsSource正在使用中。 「 – user2323308

+0

更新了我的答案,但基本上你忘了將列裝入'DataGrid.Columns' – dkozl

+0

感謝您的回覆。從我的項目的其他代碼拋出同樣的錯誤。你能告訴我爲什麼會出現此錯誤「在ItemsSource正在使用時,操作無效。改爲使用ItemsControl.ItemsSource訪問和修改元素。「 – user2323308