gpt4 book ai didi

wpf - ListView 的 ItemsPanelTemplate 显然错误地抛出异常

转载 作者:行者123 更新时间:2023-12-04 23:14:42 27 4
gpt4 key购买 nike

我创建了一个用户控件,其中包含一个带有自定义 ItemsPanelTemplate 的 ListView。

<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。当我使用组时,我不能简单地写

Start={Binding Path=.Start}

因此我使用了上面的代码。但是,如果我将 Start 的绑定(bind)更改为此,我会得到一个异常:

ItemsPanelTemplate 的 VisualTree 必须是单个元素。

显然,ItemsPanelTemplate 只有一个元素。

那么可能是什么问题呢?我的自定义面板不创建任何元素。它只是安排它们。

最佳答案

您收到此异常可能是因为您试图将“Children”添加到 TimeLinePanel(或者您正在覆盖面板的可视化树并在“VisualChildrenCount”中返回 1 以外的内容)。遗憾的是,由于 ItemsPanelTemplate,如果面板是在 ItemsControl 中创建的,则您无法修改面板的“Children”属性。在 ItemsControl 之外,没有问题。

或者,您可以将 ListView 的模板覆盖为如下所示的内容 - 它适用于我的情况,并消除了异常。

<ListView.Template>
<ControlTemplate>
<cd:TimeLinePanel IsItemsHost="True" UnitsPerSecond="..."/>
<ControlTemplate>
</ListView.ItemsPanel>

有一篇 CodeProject 文章 ( http://www.codeproject.com/KB/WPF/ConceptualChildren.aspx ) 提供了有关此行为的一些详细信息,这可能有助于您理解为什么会这样。

关于wpf - ListView 的 ItemsPanelTemplate 显然错误地抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1343205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com