我有一个带有两个字符串数组的对象。对象是绑定到列表框的数据。一个列表绑定为列表的ItemsSource。另一个,这是导致我麻烦的事情,需要绑定到组合框,该组合框是设置为列表的ItemTemplate的DataTemplate的一部分。基本上,列表框中的每个项目都具有第一个列表的对应元素和包含第二个列表的组合框。换句话说,列表中的每个项目都具有相同的选择组合框。
问题来自这样一个事实,即DataTemplate是第一个列表的数据绑定。我期待DataTemplate被数据绑定到包含两个列表的对象。现在,随着这种情况的发生,我无法弄清楚我需要在DataContext的“父”处获得什么样的绑定语法,如果可能的话。
有人能指出我正确的方向吗?
谢谢!
答案 0 :(得分:2)
如果我正确理解你,你可以将ListBox的DataContext设置为一个类的实例(在我的例子中,我在代码中执行:list.DataContext = myclass;)并且你想设置ItemSource您的列表框中的列表(即项目)和组合框的项目源到类中的另一个列表(即值)。这是我的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实例,添加了Items和Values,并将实例设置为列表框的DataContext。
答案 1 :(得分:1)
我认为你不想做你想做的事。你在寻求痛苦。
您可能想要做的是在集合中的每个项目中引用静态集合,其中包含ComboBox的子集合。所以:
//Pseudocode
TopLevelEntity
{
SubLevelEntity[] SubItemsForComboBox;
}
对于每个“TopLevelEntity”,您都可以使用组合框的项目集合进行准备。
<ListView ItemsSource="{StaticResource MyCollectionOfTopLevelEntities}">
<ItemTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding SubItemsForComboBox} />
</DataTemplate>
</ItemTemplate>
</ListView>
按照我的方式,我没有验证这个代码,它甚至可能没有编译,但理论应该是合理的。
告诉我们您的决定。
答案 2 :(得分:0)
首先,Anderson建议我建议你重新设计你的类以从外面的一些地方获得Combobox项目作为静态引用列表 但这是针对您当前场景的解决方法。 我假设你感兴趣的主要对象('Parent')是ListBox的DataContext。你想在DataTemplateLevel中引用它。想法是走到ListBox并获取DataContext
<Combobox DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" ItemsSource="{Binding YourCollection}" ....