1

I want to show Employee List data in the Data Grid. When I run below code empty grid is displayed.

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" });
            }
        }
    }

Output Should Be:

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

1 回答 1

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>

在你设置ItemsSourceEmloyeeInfo全班并且你想指向你的那一刻,你ObservableCollection<Employee>也忘了把你的专栏包装在DataGrid.Columns

于 2013-08-22T12:57:58.023 回答