将项目列表绑定到数据网格单元
本文关键字:数据网 网格 单元 数据 项目 列表 绑定 | 更新日期: 2023-09-27 18:02:27
我在WPF中有一个DataGrid,它应该显示图书的集合。书是这样的:
public class Book
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string title = "";
public string Title
{
get
{
return title;
}
set
{
title = value;
OnPropertyChanged("Title");
}
}
private List<Writer> writers = new List<Writer>();
public List<Writer> Writers
{
get
{
return writers;
}
set
{
writers = value;
OnPropertyChanged("Writers");
}
}
public Book() { }
public Book(string bookTitle)
{
this.Title = bookTitle;
}
}
下面是Writer类:
public class Writer
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string fullname = "";
public string Fullname
{
get
{
return fullname;
}
set
{
fullname = value;
OnPropertyChanged("Fullname");
}
}
private string forename = "";
public string Forename
{
get
{
return forename;
}
set
{
forename = value;
OnPropertyChanged("Forename");
}
}
private string surename = "";
public string Surename
{
get
{
return surename;
}
set
{
surename = value;
OnPropertyChanged("Surename");
}
}
public Writer() { }
public Writer(string writersForename, string writersSurename)
{
this.Forename = writersForename;
this.Surename = writersSurename;
this.Fullname = string.Format("{0} {1}", this.Forename, this.Surename);
}
}
现在我想在DataGrid的单个单元格中显示编写者。像这样:
Title | Writer
------------------------
Book1 | Writer1
| Writer2
------------------------
Book2 Writer1
...
但是,如果我试图将列表绑定到单元格,它只显示"收集"在单元格中作为值。
这是我使用的XAML:
<ToolKit:DataGrid x:Name="dataGrid1" DataContext="{StaticResource ItemCollectionViewSource}" IsReadOnly="True" ItemsSource="{Binding}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" AutoGenerateColumns="False" >
<ToolKit:DataGrid.Columns>
<ToolKit:DataGridTextColumn Header="Title" Binding="{Binding Path=Title}" />
<ToolKit:DataGridTextColumn Header="Writer" Binding="{Binding Path=Writers}" />
</ToolKit:DataGrid.Columns>
</ToolKit:DataGrid>
我已经尝试将单元格绑定到"Writers"。全名",但这也行不通。你能帮我一下吗,我找不到这种绑定的例子。
的问候SyLuS
您可以使用ItemsControl
创建DataGridTemplateColumn
列,这将绑定到Writers
列表:
<ToolKit:DataGridTemplateColumn Header="Writer">
<ToolKit:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Writers}" DisplayMemberPath="Fullname"/>
</DataTemplate>
</ToolKit:DataGridTemplateColumn.CellTemplate>
</ToolKit:DataGridTemplateColumn>