【问题标题】:How to add ItemsSource to Combobox nested in ListBox Template from codebehind?如何从代码隐藏将 ItemsSource 添加到嵌套在 ListBox 模板中的 Combobox?
【发布时间】:2016-04-09 00:43:42
【问题描述】:

我对嵌套在ListBox 中的ComboBox 有一些问题。我想将相同的ItemsSource(从数据库获得,从代码隐藏添加)添加到在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

【问题讨论】:

  • Sb 建议将组合框 ItemsSource 设置为 ListBox.DataContext 并将 Items 设置为 DataContext 但我不知道为什么删除了这个答案。 ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}},Path=DataContext}"

标签: c# wpf xaml combobox listbox


【解决方案1】:

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

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

【讨论】:

  • 但不幸的是没有。这个listbox 是在数据库中的三个表上构建的——一个是TYPE1,一个是TYPE2,它们之间的东西类似于哈希表,我无法更改TYPE1TYPE2 类。
  • 那么你应该创建一个合适的视图模型。在网上搜索 MVVM。
  • 这可能比在ListBox 中使用DataContext 作为Combobox ItemsSource 的容器更合适。感谢您的帮助。
猜你喜欢
  • 2011-04-06
  • 1970-01-01
  • 2013-02-19
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多