如果您可以指定列而不是自動生成它們,這可能非常容易。
下面是一個例子:
<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
爲Employees
和ItemsCollectionB
和ItemsCollectionC
爲Dogs
和Cats
。它仍然使用ToString
來顯示我覆蓋的Dogs
和Cats
對象,但是您可以簡單地將DataTemplate
設置爲列中的列表框,以決定如何顯示模型。請注意0上的AutoGenerateColumns="False"
以避免創建兩次列。
希望這有助於
這是因爲它不知道如何顯示這些集合。它基本上在你的ItemsCollectionB和ItemsCollectionC上調用'.ToString()'。我們需要更多信息來回答您的問題。正如@geedubb所問,你想爲這些顯示什麼? – gleng
現在它告訴我有一個集合,我想要集合的每個項目中的所有值,即顯示集合中每個項目中存在的稱爲名稱或值的屬性(爲清晰起見編輯) – Oliver
@奧利弗你**有**自動生成列?因爲如果不是這很容易 –