我在 HubSection 中有一个 ListBox,其项目绑定到通过后面的代码添加到我的 DefaulViewModel 的类玩家".首先,我简单地将一个 TextBox 绑定到我的类players"的属性PlayerName".现在我想添加一个组合框,其中包含一些不属于类播放器的项目.
I have a ListBox inside a HubSection, whose Items are bound to a class "players" added to my DefaulViewModel via code behind. First I simply put a TextBox bound to the property "PlayerName" of my class "players". Now I would like to add a ComboBox with some items that are NOT part of the class players.
有可能吗?我认为在 ComboBox 中定义 ItemsSource 会覆盖 ListBox 的 ItemsSource,但没有显示任何内容.
Is it possible ? I thought that definind an ItemsSource in the ComboBox would sort of override the ItemsSource of the ListBox, but nothing displays.
整个页面的DataContext定义如下:
The DataContext of the whole page is defined like so:
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
那么HubSection就是这样的:
Then the HubSection is like so:
<HubSection x:Name="HubSec1">
<DataTemplate>
<ListBox x:Name="ListBox1" ItemsSource="{Binding players}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding Path=PlayerName, Mode=TwoWay}"/>
<ComboBox ItemsSource="{Binding Path=ListOfElements}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</HubSection>
如果我以相同的方式定义 ComboBox 但在 ListBox 之外,它将正确显示ListOfElements"的字符串元素.但是在这个 ListBox 中,ComboBox 是空的.所以我的猜测是,已经为 ListBox 定义了 ItemsSource,不可能覆盖它.
If I define the ComboBox in the same way but outside the ListBox, it will display the string elements of "ListOfElements" properly. But in this ListBox, the ComboBox is empty. So my guess is that having defined an ItemsSource for the ListBox, it is not possible to override it.
我试图定义一个 DataTemplate 但没有成功,但这可能是一个很好的解决方案(我没有正确进行)
I have tried to define a DataTemplate but was not successful doing so, but it might be the good solution (and I did not proceed properly)
我错过了什么?
ComboBox 项是一个 ObservableCollection.它不是玩家"类的一部分.这是我如何将这些元素添加到 DefaultViewModel
Edit : The ComboBox items is an ObservableCollection. It is not part of the "players" class. Here is how I added these elements to the DefaultViewModel
DefaultViewModel.Add("players", players);
DefaultViewModel.Add("MyItemsList", ListOfElements);
您可以向上走可视化树并绑定到祖先数据上下文:
You can walk up the visual tree and bind to an ancestors datacontext:
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
前:
{Binding Path=ListOfItems, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}
这应该为您提供列表框具有的数据上下文,因此假设您的 ListOfItems 存在于该数据上下文中.
that should give you the datacontext that the listbox has, so assuming your ListOfItems exists in that data context.
或者你可以命名你的控件,然后通过元素名称绑定到它的数据上下文:
Or you can name your control, and then bind to its datacontext by element name:
{Binding ElementName=mySourceElement,Path=ListOfItems}
这篇关于如何绑定到与已指定的 ItemsSource 不同的 ListBox 内的源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!