我创建了一个用户控件,它包含一个带有自定义ListView的ItemsPanelTemplate。
<UserControl x:Class="..."
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="thisUserControl">
<ListView ItemsSource="{Binding Source={StaticResource cvs}}"
Name="mainListView">
<ListView.GroupStyle>
<GroupStyle>
...
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<cd:TimeLinePanel UnitsPerSecond="{Binding ElementName=thisUserControl,Path=DataContext.UnitsPerSecond}" Start="{Binding ElementName=thisUserControl, Path=DataContext.Start}"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>DataContext的UserControl有两个属性Start和UnitsPerSecond。因为我正在使用组,所以我不能简单地写
Start={Binding Path=.Start}因此,我使用了上面的代码。但是,如果我更改了Start的绑定,就会得到一个例外:
VisualTree of ItemsPanelTemplate必须是一个单一元素。
显然,ItemsPanelTemplate只有一个元素。
那么有什么问题呢?我的自定义面板不创建任何元素。只是安排了他们。
发布于 2009-09-17 17:26:47
您收到此异常可能是因为您试图将“子”添加到TimeLinePanel (或者您正在覆盖面板的可视树并在“VisualChildrenCount”中返回1以外的内容)。遗憾的是,如果面板是在ItemsControl中创建的,则不能修改它的“ItemsPanelTemplate”属性。在ItemsControl之外,没有问题。
或者,您可以覆盖ListView的模板如下所示-它在我的情况下工作,并消除异常。
<ListView.Template>
<ControlTemplate>
<cd:TimeLinePanel IsItemsHost="True" UnitsPerSecond="..."/>
<ControlTemplate>
</ListView.ItemsPanel>有一篇CodeProject文章(http://www.codeproject.com/KB/WPF/ConceptualChildren.aspx)给出了关于这种行为的一些细节,这可能有助于您理解为什么会出现这种情况。
https://stackoverflow.com/questions/1343205
复制相似问题