有很多方法可以实现这一点 - 您可以尝试的一种方法是创建一个封装您想要显示的数据的视图模型 - 例如
public class EmployeeViewModel
{
private readonly Employee _employee;
public EmployeeViewModel(Employee employee)
{
_employee = employee;
}
public string Name { get { return _employee.Name; } }
public string CompanyName { get { return _employee.Company == null ? "Unemployed" : _employee.Company.CompanyName; } }
}
然后,给定IEnumerable<Employee>,您可以将员工数据投影到此视图模型中,并将其设置为 DataGrid 的 ItemsSource - 例如
IEnumerable<Employee> employees = GetEmployeesFromDatabase();
DataGrid1.ItemsSource = employees.Select(x => new EmployeeViewModel(x));
您通常会在此处通过 xaml 绑定设置 ItemsSource,而不是直接在代码中设置,但这将涉及使用父 ViewModel 设置为 View 的 DataContext,我试图让事情变得简单。
使用 DataGrid 完成此操作的另一种方法是放弃使用视图模型,直接绑定到 IEnumerable<Employee> 集合并显式设置列绑定 - 例如
<DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Employee Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Company Name" Binding="{Binding Company.Name}" />
</DataGrid.Columns>
</DataGrid>
请注意,在第二个示例中,您不会在没有员工关联公司的公司名称列中看到“失业”。
编辑:为了阐明关于从绑定到视图的“主”视图模型上的属性设置网格项目源的要点,您可以创建一个表示整个当前视图的 ViewModel 类。例如
public class MainViewModel
{
private readonly IEnumerable<Employee> _employees;
public MainViewModel(IEnumerable<Employee> employees)
{
_employees = employees;
}
public IEnumerable<Employee> Employees
{
get { return _employees; }
}
}
您可以将其设置为 Window / UserControl 的 DataContext。
例如在简单的情况下,您可以在 Window 的构造函数中执行此操作(尽管对于 WPF 应用程序而言,对数据库的调用实际上应该是异步的)。
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel(GetAllEmployees());
}
然后你可以像这样在你的 Grid 上设置绑定:
<DataGrid ItemsSource="{Binding Employees}" ...
然后,主窗口的数据上下文将用于其中包含的所有子控件,除非您在子控件上显式设置 DataContext。当您拥有具有许多属性和命令的更复杂的 ViewModel 时,这种技术会变得很有用。如果您有兴趣了解更多信息,您应该查看 MVVM 模式以及 Prism / Caliburn 框架中的一个或两个。