如何将ItemSource添加到嵌套在ListBox模板中的Combobox代码隐藏?

时间:2016-01-05 08:48:33

标签: c# wpf xaml combobox listbox

嵌套在ComboBox中的ListBox存在问题。我想将相同的ItemsSource(从数据库中获取,从代码隐藏中添加)添加到comboboxes中创建的每个ListBox,但不知道如何。任何想法如何做到这一点?

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

在codebehind中:

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

1 个答案:

答案 0 :(得分:0)

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

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