将员工列表绑定到DataGrid

本文关键字:DataGrid 绑定 列表 | 更新日期: 2023-09-27 18:28:33

我想在数据网格中显示员工列表数据。当我在代码下面运行时,会显示空网格。

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

将员工列表绑定到DataGrid

试试这个:

<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