如果您可以指定列而不是自动生成它们,这可能非常容易。
这是一个例子:
<DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding EmployeeName}"/>
<!-- Displays the items of the first collection-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding Dogs}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- Displays the items of the second collection-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding Cats}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
视图模型:
public class MainWindowViewModel : NotificationObject
{
public MainWindowViewModel()
{
Employees = new ObservableCollection<Employee>
{
new Employee { EmployeeName = "Steven"},
new Employee { EmployeeName = "Josh"},
};
}
public ObservableCollection<Employee> Employees { get; set; }
}
楷模:
public class Employee
{
public Employee()
{
Dogs = new ObservableCollection<Dog>
{
new Dog { Gender = 'M'},
new Dog { Gender = 'F'},
};
Cats = new ObservableCollection<Cat>
{
new Cat { Name = "Mitzy" , Kind = "Street Cat"},
new Cat { Name = "Mitzy" , Kind = "House Cat"}
};
}
public string EmployeeName { get; set; }
public ObservableCollection<Dog> Dogs { get; set; }
public ObservableCollection<Cat> Cats { get; set; }
}
public class Dog
{
public char Gender { get; set; }
public override string ToString()
{
return "Dog is a '" + Gender + "'";
}
}
public class Cat
{
public string Name { get; set; }
public string Kind { get; set; }
public override string ToString()
{
return "Cat name is " + Name + " and it is a " + Kind;
}
}
考虑ItemsCollectionA
asEmployees
和as和。ItemsCollectionB
_ 它仍然使用来显示我覆盖的对象,但是您可以简单地将 a设置为列中的列表框来决定如何显示您的模型。还要注意on以避免两次创建列。ItemsCollectionC
Dogs
Cats
ToString
Dogs
Cats
DataTemplate
AutoGenerateColumns="False"
DataGrid
希望这可以帮助