2013-08-22 70 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