如果您可以指定列而不是自动生成它们,那么这将非常容易。以下是一个例子:
<DataGrid ItemsSource="" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding=""/>
<!-- Displays the items of the first collection-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource=""/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- Displays the items of the second collection-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource=""/>
</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
视为
员工
,将
ItemsCollectionB
和
ItemsCollectionC
视为
狗
和
猫
。仍然使用
ToString
来显示我重写的
狗
和
猫
对象,但您可以简单地设置一个
DataTemplate
来决定如何显示您的模型在列中的listBox中。还请注意在
DataGrid
上设置
AutoGenerateColumns="False"
以避免创建两次列。
希望这有所帮助。
ItemsCollectionB
和ItemsCollectionC
上调用了.ToString()
。我们需要更多信息来回答你的问题。正如@geedubb所问,你想要为这些显示什么? - gleng