如何从codeehind将ItemsSource添加到嵌套在ListBox Template中的组合框中

本文关键字:Template ListBox 组合 嵌套 codeehind 添加 ItemsSource | 更新日期: 2023-09-27 18:29:03

我对嵌套在ListBox中的ComboBox有一些问题。我想将相同的ItemsSource(从数据库中获得,从codeehind中添加)添加到ListBox中创建的每个comboboxes中,但不知道如何添加。有什么办法吗?

</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>

在码尾:

lbxListbox.ItemsSource = observableCollectionFromDatabase;
//here should be sth to set ItemsSource for comboboxes in ListBox

如何从codeehind将ItemsSource添加到嵌套在ListBox Template中的组合框中

项目类中应该有一个集合类型属性(任何实现IEnumerable的东西都可以)。然后你可以像这样绑定组合框的ItemSource

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