我想在数据网格中显示员工列表数据。当我在代码下面运行时,显示空格。
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 :(得分: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