繁体   English   中英

如何将 ItemsControl 与多个 ItemsSource 嵌套?

[英]How to nest ItemsControl with multiple ItemsSource?

我有一个带有名称和DictionaryConfigList对象,我需要使用不同的ItemsSource嵌套ItemsControls

我试图这样做:

<ItemsControl x:Name="TestStep" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding Path=ConfigList }" HorizontalAlignment="Center" VerticalAlignment="Center">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Ictrl.Nom}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl
    ItemsSource="{Binding Path=Param}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Key}" />
                    <TextBlock Text=" : " />
                    <TextBlock Text="{Binding Path=Value}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ItemsControl>

当我启动我的应用程序时,我收到了这个错误:

System.Windows.Markup.XamlParseException:“向“System.Windows.Controls.ItemCollection”类型的集合添加值引发异常。 ' 行号 '25' 和行位置 '14'。 '

内部异常 InvalidOperationException:使用 ItemsSource 时操作无效。 使用 ItemsControl.ItemsSource 访问和编辑项目。

知道问题是什么吗?

您在ItemsControl上设置了一个ItemsSource 数据模板用于创建显示数据的控件。 然后将创建的项目放入ItemsControlItems集合中。 如果您直接在 XAML 中向ItemsControl添加元素,这也会将它们放入Items集合中。 不允许同时进行。 您可以指定ItemsSource或直接添加到Items 文档

请注意,您使用 Items 或ItemsSource属性来指定应用于生成ItemsControl内容的集合。 设置ItemsSource属性后, Items集合ItemsSource只读和固定大小

但是,在您的情况下,这不是真正的问题,因为您的标记对于您想要实现的目标是错误的。 如果您确实打算嵌套ItemsControl ,则只需更改外部ItemsControl的数据模板,以包含另一个绑定到外部数据项内的集合属性的ItemsControl 由于已经有一个TextBox ,您必须使用一个面板(例如StackPanel )来承载模板中的多个控件。

<ItemsControl x:Name="TestStep" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding Path=ConfigList }" HorizontalAlignment="Center" VerticalAlignment="Center">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Path=Ictrl.Nom}" />
                <ItemsControl ItemsSource="{Binding Path=Param}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Path=Key}" />
                                <TextBlock Text=" : " />
                                <TextBlock Text="{Binding Path=Value}" />
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如果您想拥有数据的分层视图,使用TreeView可能更合适。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM