ListView的ItemsPanelTemplate显然错误地引发了异常 [英] ItemsPanelTemplate of a ListView throws apparently wrongly 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}
因此,我使用了上面的代码.但是,如果我将Start的绑定更改为此,则会出现异常:
Thus I used the code above. But if I change the binding of Start to this I get an exception:
ItemsPanelTemplate的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.
推荐答案
您收到此异常的原因可能是您正在尝试向TimeLinePanel添加"Children"(或者您正在覆盖面板的可视树并返回除1在"VisualChildrenCount"中).遗憾的是,如果由于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屋!