2016-01-05 33 views
0

我有一些問題,ComboBox嵌套在ListBox。我想添加相同的ItemsSource(從數據庫中獲得,從代碼隱藏中添加)到在ListBox中創建的comboboxes,但不知道如何。任何想法如何做到這一點?如何添加ItemsSource到代碼隱藏嵌套在ListBox模板中的Combobox?

</Window.Resources> 
    <Style x:Key="lbxKey" TargetType="ListBox"> 
     <Setter Property="ItemsPanel"> 
      <Setter.Value> 
       <ItemsPanelTemplate> 
        <StackPanel/> 
       </ItemsPanelTemplate> 
      </Setter.Value> 
     </Setter> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <DataTemplate DataType="{x:Type Type1}"> 
        <StackPanel Orientation="Horizontal" Width="Auto" HorizontalAlignment="Stretch"> 
         <TextBlock TextTrimming="CharacterEllipsis" Width="200" Text="{Binding NAMETYPE1}" HorizontalAlignment="Left"></TextBlock> 
         <ComboBox HorizontalAlignment="Stretch" Tag="{Binding IDTYPE1}"> 
          <ComboBox.ItemsSource> 
           <!-- no idea what should be here or even if this is needed --> 
          </ComboBox.ItemsSource> 
          <ComboBox.ItemTemplate> 
           <DataTemplate DataType="{x:Type Type2}"> 
            <StackPanel Orientation="Horizontal" Width="100"> 
             <TextBlock Text="{Binding NAMETYPE2}" TextTrimming="CharacterEllipsis"/> 
            </StackPanel> 
           </DataTemplate> 
          </ComboBox.ItemTemplate> 
         </ComboBox> 
        </StackPanel> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 

在代碼隱藏:

lbxListbox.ItemsSource = observableCollectionFromDatabase; 
//here should be sth to set ItemsSource for comboboxes in ListBox 
+0

銻建議設置組合框'ItemsSource'爲'ListBox.DataContext'並設置項目以DataContext的,但我不知道爲什麼這個答案被刪除。 'ItemsSource =「{Binding RelativeSource = {RelativeSource FindAncestor,AncestorType = {x:Type ListBox}},Path = DataContext}」' – Kelk

回答

0

應該有你的項目類集合型屬性(任何實現IEnumerable都行)。然後,你會綁定組合框的ItemSource這樣的:

<ComboBox Tag="{Binding IDTYPE1}" ItemsSource="{Binding ITEMS}" ...> 
+0

但是不幸的是沒有。這個'listbox'建立在數據庫的三個表上 - 一個使用'TYPE1',一個使用'TYPE2',類似於它們之間的哈希表,我不能改變'TYPE1'和'TYPE2'類。 – Kelk

+0

然後你應該創建一個合適的視圖模型。在網絡上搜索MVVM。 – Clemens

+0

這可能比'ListBox'中的'DataContext'作爲'Combobox ItemsSource'的容器更合適。感謝幫助。 – Kelk

相關問題