2009-07-27 73 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}" ....