2012-04-12 45 views
2

我有一個包含兩個表的數據集,這對於很多父子關係來說是簡單的。例如;如何在wpf數據網格中顯示來自數據集的相關數據

Parent Table 
ParentId (int) 
Name  (string) 

Child Table 
ChildId (int) 
ParentId (int) 
Name  (string) 

在此數據集我已經得到了家長和孩子的父母id字段之間建立的關係(ParentChildRelation)。如果我以編程方式執行Parent.getChildRows()調用,則會看到正確的相關子記錄,因此我知道這種關係很好。

我需要顯示具有父行的列表的數據網格,並具有另一個單獨的datagrid,顯示所選父級的子記錄列表。

到目前爲止,我在代碼窗口後面我有

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"] ; 
     } 
    } 

我還設置爲窗口,以自身的窗口構造例如在DataContext上;

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露面。

我綁定這個網格到datarelation名稱是否正確?

如果我綁定到我的窗口上的另一個屬性;

public DataView ChildrenView 
    { 
     get 
     { 
      return this.ParentChildDataSet.Tables["Child"].DefaultView; 
     } 
    } 

然後我看到所有的記錄,不管父母爲你所期望的。

感謝任何人都可以給我的指針。

回答

1

當你返回一個DataView時它正在工作,但是顯示全部。

在這裏,您正在返回一個DataRelation

ItemsSource="{Binding Path=ParentChildRelation}" 

你需要返回一個DataView

使用的關係產生數據視圖

DataRowView.CreateChildView方法(的DataRelation)

+0

而這只是爲什麼這個投票下來? – Paparazzi 2012-04-12 18:39:03

+0

不知道爲什麼它是downvoted或由誰,謝謝你的信息,但沒有辦法通過xaml直接綁定到子視圖,而不是調用CreateChildView方法? – 2012-04-13 08:09:08

+0

我看到一個問號。有問題嗎?它有用嗎? – Paparazzi 2012-04-13 12:04:57

1

我無法制定出可接受的答案。我的情況與此處描述的情況相同:2個表格,關係,2個數據網格。

我特地到CreateChildView方法,但我缺少一個關鍵的地方。我目前用於獲取childview代碼:

public DataView ChildView { 
    get { 
     return ParentChildRelation.ParentTable.DefaultView[0].CreateChildView("regels") 
    } 
} 

的問題是雙重的,首先我明明有索引固定的,這意味着我總是得到parenttable的第一行的childview。其次,我在獲取時,一個新的行中的父視圖中選擇(ChildView只被調用在初始化時)新的子視圖慘遭失敗。

我的XAML:

<Grid> 
    <DataGrid 
     ItemsSource="{Binding Path=ParentView}" 
     AutoGenerateColumns="True" 
     Name="dataGrid1" 
    /> 

    <DataGrid 
     ItemsSource="{Binding Path=ChildView}" 
     AutoGenerateColumns="True" 
     Name="dataGrid2" 
    /> 
</Grid> 

我想使這個XAML的解決方案,避免寫事件處理器更新childview。我嘗試過使用DataContext,但沒有得到任何答案,關於如何利用數據集和關係來利用這個結構的文檔非常渺茫(讓我想知道我是否要走正確的道路)。

+0

嘿,那裏!我相信你最好把它作爲一個單獨的問題發佈,並說明爲什麼這個解決方案不起作用。這可能比將它作爲對已經解決的問題的回答更有幫助,它不會像注意到的那樣。乾杯! – 2017-03-02 21:55:04

相關問題