2009-07-27 72 views
1

我有一個有兩個字符串數組的對象。該對象是綁定到列表框的數據。一個列表被綁定爲列表的ItemsSource。另一個是導致我麻煩的事情,需要綁定到一個組合框,該組合框是設置爲列表的ItemTemplate的DataTemplate的一部分。基本上,列表框中的每個項目都有第一個列表的相應元素和包含第二個列表的組合框。換句話說,列表中的每個項目都有相同的選擇組合框。獲取數據綁定對象的「父」?

問題出在這樣的事實,即DataTemplate數據綁定在第一個列表中。我期待DataTemplate被數據綁定到包含兩個列表的對象。現在,發生這種情況時,我無法弄清楚我需要在DataContext的「父」處獲得什麼樣的綁定語法,如果這甚至是可能的話。

有人能指出我正確的方向嗎?

謝謝!

+0

需要查看所有的XAML來幫助您處理這個問題。 – Charlie 2009-07-27 19:19:15

回答

2

如果我正確理解你,你可以設置你的ListBox的DataContext爲一個類的實例(在我的例子中,我在代碼中做:list.DataContext = myclass;),並且你想設置您的列表框的ItemSource添加到類中的列表(即Items)和組合框的itemssource到類中的另一個列表(即Values)中。這裏是我的XAML,似乎工作:

<ListBox Name="list" ItemsSource="{Binding Items}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <TextBlock Text="{Binding}"/> 
       <ComboBox ItemsSource= 
          "{Binding RelativeSource={RelativeSource FindAncestor, 
                AncestorType={x:Type ListBox}}, 
            Path=DataContext.Values}" 
       /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

和繼承人是我綁定到類:

public class AClass 
{ 

    protected List<string> _Items; 
    public List<string> Items 
    { 
     get 
     { 
      if (_Items == null) 
      { 
       _Items = new List<string>(); 
      } 
      return _Items; 
     } 
    } 


    protected List<string> _Values; 
    public List<string> Values 
    { 
     get 
     { 
      if (_Values == null) 
      { 
       _Values = new List<string>(); 
      } 
      return _Values; 
     } 
    } 
} 

在代碼中,我創建ACLASS的實例,添加項目和值,並設置實例添加到列表框的DataContext中。

1

我不認爲你想做你想做的事情。你在問痛苦。

您可能想要做的是在集合中的每個項目中引用靜態集合,其中包含ComboBox的子集合。所以:

//Pseudocode 
TopLevelEntity 
{ 
    SubLevelEntity[] SubItemsForComboBox; 
} 

這種方法對於每個「TopLevelEntity」,您都會準備好您的組合框的項目集合。

<ListView ItemsSource="{StaticResource MyCollectionOfTopLevelEntities}"> 
    <ItemTemplate> 
     <DataTemplate> 
      <ComboBox ItemsSource="{Binding SubItemsForComboBox} /> 
     </DataTemplate> 
    </ItemTemplate> 
</ListView> 

正如我的方式,我沒有驗證這個代碼,它可能甚至沒有編譯,但理論應該是健全的。

讓我們知道您決定做什麼。

+0

從我的建議可以理解,缺點是每個項目都會有一個重複的組合框選項列表。 – djcouchycouch 2009-07-27 20:35:29

+0

從技術上講,您可以將它們全部設置爲與收藏品的相同實例相同,但重點在於。 – 2009-07-27 21:11:29

0

首先,因爲安德森建議我建議您重新設計您的課程,以從靜態引用列表以外的某些地方獲取Combobox項目 但是,這是您當前場景的解決方法。 我假設你感興趣的主要對象('Parent')是ListBox的DataContext。你想在DataTemplateLevel中引用它。想法是走到列表框並獲取DataContext

<Combobox DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" ItemsSource="{Binding YourCollection}" ....