【问题标题】:Binding a ListBox to the elements of a collection in a collection将 ListBox 绑定到集合中的集合元素
【发布时间】:2014-05-03 11:53:24
【问题描述】:

我在将 ListBox 绑定到集合中的集合元素时遇到了一些问题。让我解释一下:

我有一个名为testsCollection 的集合ObservableCollection<Test>。每个测试都包含一个名为 LogEventsObservableCollection<LogEvent>。每个LogEvent 都有一个Message,我需要在ListBox 中显示。

我需要在每个“测试”中的每个“LogEvent”中显示每个“消息”。它必须显示在一个平面列表中,所以我使用的是 ListBox。

以下是我尝试过的总结:

DataContext = testCollection; // testCollection is an ObservableCollection<Test>

我把它放在 XAML 中:

<ListBox ItemsSource="{Binding LogEvents}" ItemTemplate="{StaticResource stepItemTemplate}">

最后,这里是ItemTemplate,stepItemTemplate:

<DataTemplate x:Key="stepItemTemplate">
    <TextBlock Text="{Binding Message}"></TextBlock>
</DataTemplate>

这“有效”,但它只显示第一个测试的 LogEvents 中的消息。但是我需要显示每个测试的每个 LogEvent 的每个消息。而且我不知道该尝试什么了:(

【问题讨论】:

    标签: c# wpf data-binding binding listbox


    【解决方案1】:

    当你想绑定这样的场景时,你应该使用 Usser ItemsControl

    <ListBox ItemsSource="{Binding testsCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Message}" FontSize="20" />
                        <ItemsControl ItemsSource="{Binding LogEvents}" Margin="0 20 0 0">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Border BorderBrush="Blue" BorderThickness="2">
                                    <TextBlock Text="{Binding Message}" FontSize="20" />
                                </Border>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
    
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    

    【讨论】:

    • 谢谢,我会努力的!
    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多