![](/img/trans.png)
[英]How to Bind ItemsSource of ListBox which is a Child of ItemsControl?
[英]How to nest ItemsControl with multiple ItemsSource?
我有一个带有名称和Dictionary
的ConfigList
对象,我需要使用不同的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
。 数据模板用于创建显示数据的控件。 然后将创建的项目放入ItemsControl
的Items
集合中。 如果您直接在 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.