2017-01-07 13 views
0

私はoptionsitemsの2つのテーブルを持っています。 1つの項目は複数のオプションに関連付けられています。WPFで関連するテーブルをバインドする方法は?

table relationship image

は、私は、ネストされたListBox s内の項目とそのオプションを表示します。問題は、内部のListBoxは物を表示しないということです。私はたぶんItemsSourceを正しく束縛しなかったと思います。どのようにそれをバインドするには?以下

私の試み:アイテムの

<Window.Resources> 
    <local:TaxAccessmentDataSet x:Key="taxAccessmentDataSet"/> 
    <CollectionViewSource x:Key="itemsViewSource" Source="{Binding items, Source={StaticResource taxAccessmentDataSet}}"/> 
    <CollectionViewSource x:Key="itemsoptionsViewSource" Source="{Binding FK_options_items, Source={StaticResource itemsViewSource}}"/> 
</Window.Resources> 
<ListBox x:Name="listBox"ItemsSource="{Binding}" DataContext="{StaticResource itemsViewSource}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Expander x:Name="expander" Header="{Binding name}"> 
       <ListBox ItemsSource="{Binding}" DataContext="{StaticResource itemsoptionsViewSource}" DisplayMemberPath="name"> 
       </ListBox> 
      </Expander> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

答えて

2

内部のListBoxのDataContextは、アイテムを表すDataRowViewになります。データバインディングを使用してこのアイテムの対応するオプションを表示できるようにするには、これらのオプションのコレクションを返すパブリックプロパティを公開する必要があります。 DataRowViewクラスでは、純粋なXAMLではこれを行うことはできません。

しかし、あなたは、ListBoxコントロールのLoadedイベントを処理し、オプションのためのDataViewを作成することができ、自分自身:

<ListBox x:Name="listBox" ItemsSource="{Binding}" DataContext="{StaticResource itemsViewSource}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Expander x:Name="expander" Header="{Binding name}"> 
       <ListBox DisplayMemberPath="name" Loaded="ListBox_Loaded" /> 
      </Expander> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

private void ListBox_Loaded(object sender, RoutedEventArgs e) 
{ 
    ListBox inner = sender as ListBox; 
    if (inner != null) 
    { 
     DataRowView drv = inner.DataContext as DataRowView; 
     if (drv != null) 
     { 
      DataView childView = drv.CreateChildView(drv.DataView.Table.ChildRelations[0]); 
      //or drv.CreateChildView(drv.DataView.Table.ChildRelations["FK_options_items"]); 
      inner.ItemsSource = childView; 
     } 
    } 
} 
+0

私はこれを試して、それは動作しませんでした。 'childView'は空で、' optionsDataTable'である 'childView.Table'も空です。しかし、私の 'options'テーブルにはデータがあります。 –

+0

データの関係がどのように設定されているかを説明する(投稿する)必要があります。もちろん、これを有効にするには、テーブル間に有効な関係を設定する必要があります。 MSDNの例を確認してください:https://msdn.microsoft.com/en-us/library/system.data.datatable.childrelations(v=vs.110).aspx – mm8

+0

私は 'optionsTableAdapter'を' 'options'テーブルをFill()します。今はデータがありますが、 'childView'はまだ空です。 –

0

DataContextはもう親ではありません - それは、すでにあなたのアイテムです。つまり、あなたの図に示すように、このプロパティoptionitemsにネストされたListBoxの項目を結合し

<ListBox ItemsSource="{Binding items}" DisplayMemberPath="name"> 

<ListBox ItemsSource="{Binding}" DataContext="{StaticResource itemsoptionsViewSource}" DisplayMemberPath="name"> 

を変更する必要があります。

+0

DataRowViewは、「アイテム」という名前のパブリックプロパティを持っていないので、これは動作しません。あなたにバインドしようとしています... – mm8

+0

はい。私は今これを試しました。それはうまくいかなかった。 –

関連する問題