如何在WPF DataGrid中显示数据集中的相关数据 [英] How to display related data from dataset in wpf datagrid
问题描述
我有一个包含两个表的数据集,这是一个简单的一对多父子关系.例如;
I've got a dataset with two tables, a simple one to many parent child relationship going on. eg;
Parent Table
ParentId (int)
Name (string)
Child Table
ChildId (int)
ParentId (int)
Name (string)
在此数据集中,我在父ID字段的父子之间建立了一个关系(ParentChildRelation).而且,如果我以编程方式进行Parent.getChildRows()调用,则会看到正确的相关子记录,因此我知道这种关系很好.
In this dataset I've got a relationship (ParentChildRelation) set up between the parent and child on the parent id field. And if I programtically do a Parent.getChildRows() call I see the correct related child records so I know the relationship is good.
我需要显示一个带有父行列表的数据网格,并让另一个单独的数据网格显示所选父级的子记录列表.
I need to display a datagrid with a list of the parent rows and have another separate datagrid displaying the list of child records for the selected parent.
到目前为止,在窗口中我背后的代码是
So far on my window in code behind I have
private DataSet _parentChildDataSet;
public DataSet ParentChildDataSet
{
get
{
return _parentChildDataSet;
}
set
{
_parentChildDataSet = value;
}
public DataView ParentView
{
get
{
return this.ParentChildDataSet.Tables["Parent"].DefaultView;
}
}
public DataRelation ParentChildRelation
{
get
{
return this.ParentChildDataSet.Relations["Parent_Child"] ;
}
}
我还在Windows构造函数中将窗口的数据上下文设置为其自身;
I also set the datacontext for the window to itself in the windows constructor eg ;
this.DataContext = this;
在我的xaml中
<Grid>
<DataGrid ItemsSource="{Binding Path=ParentView}" AutoGenerateColumns="True" Name="dataGrid1">
</DataGrid>
<DataGrid ItemsSource="{Binding Path=ParentChildRelation}" Name="dataGrid2" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" />
</DataGrid.Columns>
</DataGrid>
</Grid>
但是我无法在dataGrid2中显示任何子记录.
However I cannot get any child records to show up in dataGrid2.
我正在将此网格绑定到datarelation名称,这正确吗?
I'm binding this grid to the datarelation name is this correct?
如果我绑定到窗口上的另一个属性;
if I bind to another property on my window ;
public DataView ChildrenView
{
get
{
return this.ParentChildDataSet.Tables["Child"].DefaultView;
}
}
然后,我会看到所有记录,而与您期望的父级无关.
then I see all the records regardless of the parent as you would expect.
感谢任何人都可以给我的指导.
Thanks for any pointers anyone can give me.
推荐答案
当您返回DataView时,它正在工作,但会全部显示.
When you return a DataView it is working but displays all.
这里您要返回一个DataRelation
Here you are returning a DataRelation
ItemsSource="{Binding Path=ParentChildRelation}"
您需要返回一个DataView
You need to return a DataView
使用该关系生成DataView
Use the relation to produce the DataView
DataRowView.CreateChildView方法(DataRelation)
DataRowView.CreateChildView Method (DataRelation)
这篇关于如何在WPF DataGrid中显示数据集中的相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!