C# 如何从codebehind向嵌套在ListBox模板中的Combobox添加ItemsSource?

C# 如何从codebehind向嵌套在ListBox模板中的Combobox添加ItemsSource?,c#,wpf,xaml,combobox,listbox,C#,Wpf,Xaml,Combobox,Listbox,我对嵌套在列表框中的组合框有一些问题。我想将相同的ItemsSource(从数据库中获取,从codebehind中添加)添加到列表框中创建的每个组合框中,但不知道如何添加。有什么办法吗 </Window.Resources> <Style x:Key="lbxKey" TargetType="ListBox"> <Setter Property="ItemsPanel"> <Setter.Value>

我对嵌套在列表框中的组合框有一些问题。我想将相同的
ItemsSource
(从数据库中获取,从codebehind中添加)添加到
列表框中创建的每个
组合框中,但不知道如何添加。有什么办法吗

</Window.Resources>
    <Style x:Key="lbxKey" TargetType="ListBox">
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate DataType="{x:Type Type1}">
                    <StackPanel Orientation="Horizontal" Width="Auto" HorizontalAlignment="Stretch">
                        <TextBlock TextTrimming="CharacterEllipsis" Width="200" Text="{Binding NAMETYPE1}" HorizontalAlignment="Left"></TextBlock>
                        <ComboBox HorizontalAlignment="Stretch" Tag="{Binding IDTYPE1}">
                            <ComboBox.ItemsSource>
                                <!-- no idea what should be here or even if this is needed -->
                            </ComboBox.ItemsSource>
                            <ComboBox.ItemTemplate>
                                <DataTemplate DataType="{x:Type Type2}">
                                    <StackPanel Orientation="Horizontal" Width="100">
                                        <TextBlock Text="{Binding NAMETYPE2}" TextTrimming="CharacterEllipsis"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ComboBox.ItemTemplate>
                        </ComboBox>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

item类中应该有一个集合类型属性(任何实现
IEnumerable
的属性都可以)。然后将组合框的
ItemSource
绑定如下:

<ComboBox Tag="{Binding IDTYPE1}" ItemsSource="{Binding ITEMS}" ...>


但不幸的是没有。这个
listbox
是在数据库中的三个表上构建的-一个是
TYPE1
,一个是
TYPE2
,它们之间有一些类似于哈希表的东西,我不能更改
TYPE1
TYPE2
类。然后您应该创建一个合适的视图模型。在web上搜索MVVM。这可能比在
ListBox
中使用
DataContext
作为
组合框项目资源的容器更合适。感谢您的帮助。Sb建议将combobox
ItemsSource
设置为
ListBox.DataContext
,并将项目设置为DataContext,但我不知道为什么删除了此答案
ItemsSource=“{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBox}},Path=DataContext}”
<ComboBox Tag="{Binding IDTYPE1}" ItemsSource="{Binding ITEMS}" ...>