ListView的ItemsPanelTemplate抛出一个例外 [英] ItemsPanelTemplate of a ListView throws apperently worngly an exception
问题描述
我创建了一个包含具有自定义ItemsPanelTemplate的ListView的用户控件。
I created a user control which contains a ListView with a custom 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>
UserControl的DataContext有两个属性Start和UnitsPerSecond。当我使用组时,我不能简单地写
The DataContext of the UserControl has two properties Start and UnitsPerSecond. As I am using groups I cannot simply write
Start={Binding Path=.Start}
因此,我使用了上面的代码。但是,如果我将开始的绑定更改为此,我会得到一个例外:
Thus I used the code above. But if I change the binding of Start to this I get an exception:
ItemsTanelTemplate的VisualTree必须是单个元素。
显然,ItemsPanelTemplate只有一个元素。
Obviously the ItemsPanelTemplate has got just a single element.
那么可能是什么问题?我的自定义面板不创建任何元素。
So what could be the problem? My custom panel does not create any elements. It just arranges them.
提前感谢
推荐答案
你正在收到此异常,可能是因为您尝试将Children添加到TimeLinePanel(或者您将覆盖面板的可视化树,并在VisualChildrenCount中返回1以外的内容)。可悲的是,如果由于ItemsPanelTemplate而在ItemsControl中创建,则不能修改面板的Children属性。在ItemsControl之外,没有问题。
You are receiving this exception probably because you are trying to add "Children" to TimeLinePanel (or you are overriding the visual tree of the panel and returning something other than 1 in "VisualChildrenCount"). Sadly, you cannot modify the "Children" property of a panel if it is created inside an ItemsControl because of an ItemsPanelTemplate. Outside of an ItemsControl, there is no problem.
或者,您可以覆盖ListView的模板,如下所示 - 它适用于我的例子,并摆脱了异常。
Alternatively, you can override the template of ListView to something like the following - it works in my case, and gets rid of the exception.
<ListView.Template>
<ControlTemplate>
<cd:TimeLinePanel IsItemsHost="True" UnitsPerSecond="..."/>
<ControlTemplate>
</ListView.ItemsPanel>
有一个CodeProject文章( http://www.codeproject.com/KB/WPF/ConceptualChildren.aspx ),其中提供了有关此行为的一些细节,这可能有助于您了解为什么就是这样。
There is a CodeProject article (http://www.codeproject.com/KB/WPF/ConceptualChildren.aspx) which gives some details on this behavior, which may help you understand why it is the case.
这篇关于ListView的ItemsPanelTemplate抛出一个例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!