Wpf 如何将ComboBoxItem添加到列表框中的ComboxBox(两者都使用数据绑定)
我找不到解决这个问题的办法。。我有一个ListBox,它的DataTemplate有一个ComboBox。数据绑定已经到位,这是一种集合集合场景。我想在所有组合框中预装一个“选择一项”。我该怎么做Wpf 如何将ComboBoxItem添加到列表框中的ComboxBox(两者都使用数据绑定),wpf,wpf-controls,Wpf,Wpf Controls,我找不到解决这个问题的办法。。我有一个ListBox,它的DataTemplate有一个ComboBox。数据绑定已经到位,这是一种集合集合场景。我想在所有组合框中预装一个“选择一项”。我该怎么做 编辑:真的不知道为什么需要代码/xaml来回答上述问题。但无论如何,下面是: <Resources> <ResourceDictionary> <DataTemplate x:Key="CategoriesDataTemplate">
编辑:真的不知道为什么需要代码/xaml来回答上述问题。但无论如何,下面是:
<Resources>
<ResourceDictionary>
<DataTemplate x:Key="CategoriesDataTemplate">
<StackPanel Orientation="vertical">
<TextBlock Text="{Binding Path=CategoryName}"></TextBlock>
<ComboBox ItemsSource="{Binding Path=Products}" Background="Transparent" SelectedValuePath="ProductId" DisplayMemberPath="ProductName">
</ComboBox>
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</Resources>
.....
<Grid..>
<ListBox ItemsSource="{Binding Categories}" ItemTemplate="{DynamicResource CategoriesDataTemplate}">
</Grid>
.....
对于每个类别,我将在下面显示类别名称及其产品的组合框。用户可以为每个类别选择一种产品。对于每个这样的组合框,我希望第一项是“选择产品”或类似的内容。
注意:我想看看是否有一种方法可以做到这一点,而不必对每个类别中的每个产品集合预先挂起一个项目(如果可能的话,我不希望干扰源集合)。某种事件处理程序方法?进一步挖掘后,得到了一个结合以下内容的解决方案: 和和。诀窍是使用CompositeCollection,所以我们可以为ComboBox同时使用静态和动态项 我的组合框现在看起来像这样(我无法让它与StackPanel资源一起工作。我是wpf的新手。有人请对StackPanel资源方法发表评论。):
code,Xaml,还有什么吗?@StefanDenchev好的,我现在添加了部分Xaml。轮到你了:)“真的不知道为什么你需要代码/xaml来回答上述问题。”:因为它有助于理解。。。如果我理解正确,就足够了。。。哈,另外两个“布莱恩”也参与了这个问题…@StefanDenchev我想我的编辑真的没有帮助。如果我正确理解了你的链接,它谈论的是显示文本,而不是“预加”一个额外的项目(我可能错了,我是wpf的新手)。我想预先挂起一个项目,而不仅仅是设置文本属性。我以belowYes的身份管理了一个解决方案,我认为只显示它就足够了,而不是在开始时显示空字段。。。很高兴你明白了。
<StackPanel.Resources>
<CollectionViewSource Source="{Binding Path=Products}" x:Key="options"/>
<!--not used. doesn't seem to be working when used DummyOption is a property in ViewModel-->
<CollectionViewSource Source="{Binding DummyOption}" x:Key="dummyOption"/>
</StackPanel.Resources>
<ComboBox Background="Transparent" SelectedValuePath="ProductId" DisplayMemberPath="ProductName" SelectedIndex="0">
<ComboBox.ItemsSource>
<CompositeCollection>
<!--works-->
<models:Product ProductName="Select" ProductId="{x:Static sys:Guid.Empty}" .../>
<!--notworking-->
<!--<ComboBoxItem Content="{Binding dummyOption}" />-->
<!--notworking-->
<!--<ComboBoxItem Content="{Binding DummyOption}" />-->
<!--notworking-->
<!--<ComboBoxItem Content="{Binding Source={StaticResource ResourceKey=dummyOption}}" />-->
<CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=Products}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>