【发布时间】:2012-01-18 10:14:41
【问题描述】:
我正在使用带有 Silverlight 的 Prism 4,并且我想使用 ItemsControl 来托管多个视图。我真的希望所有视图都包含在指定的 ItemTemplate 中,或者能够指定 ItemStyle,以便我可以使用类似 Silverlight Toolkit 中的 Expander 控件。当我尝试指定 ItemTemplate 时,会在运行时引发未处理的 System.NotSupportedException。
ItemsControl.Items must not be a UIElement type when an ItemTemplate is set.
at System.Windows.Controls.ItemsControl.MS.Internal.Controls.IGeneratorHost.GetContainerForItem(Object item, DependencyObject recycledContainer)
at System.Windows.Controls.ItemContainerGenerator.Generator.GenerateNext(Boolean stopAtRealized, Boolean& isNewlyRealized)
at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.GenerateNext(Boolean& isNewlyRealized)
at System.Windows.Controls.ItemsControl.AddContainers()
at System.Windows.Controls.ItemsControl.RecreateVisualChildren(IntPtr unmanagedObj)
代码
<ItemsControl Regions:RegionManager.RegionName="DetailsRegion">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<ContentPresenter Content="{Binding}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
【问题讨论】:
-
如何设置 ItemsSource?基于异常,听起来您正在将项目显式添加到项目控件 (itemsControl.itemsControl.Items.Add()) 而不是设置 ItemsSource,通常通过绑定或您可以通过 Codebehind (itemscontrol.ItemsSource =我的收藏)。
-
我没有在 Xaml 中设置 ItemsSource。我在 Prism4 中使用默认的 ItemsControlRegionAdapter。它将 void Adapt(IRegion region, ItemsControl regionTarget) 中的 ItemsSource 设置为:regionTarget.ItemsSource = region.Views。 region.Views 是 IViewsCollection : IEnumerable
-
你知道收藏中有什么吗?我认为这可能是问题所在,因为 SL 知道这已经是一个元素,它可能只是尝试渲染它而不是将其用作 DataTemplate 的 DataContext。
-
你的意思是什么是'in'集合?抛出异常时,集合中没有任何内容。
-
对不起,我的意思是“在”。看起来 PRISM 正在为该系列添加一些东西。例外显然是指一个项目。你能以某种方式订阅 CollectionChange 事件吗?我认为您将不得不编写自己的 IRegion 将元素包装到另一个内容中。