2009-08-27 45 views
2

我創建了一個用戶控件,其中包含一個具有自定義ItemsPanelTemplate的ListView。ListPanel的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。由於我使用的是羣組,因此我不能簡單地寫

Start={Binding Path=.Start} 

因此我使用了上面的代碼。但是,如果我將Start的綁定更改爲此,則會發生異常:

ItemsPanelTemplate的VisualTree必須是單個元素。

很明顯ItemsPanelTemplate只有一個元素。

那麼會有什麼問題呢?我的自定義面板不會創建任何元素。它只是安排他們。

回答

5

您正在接收此異常可能是因爲您正在嘗試向TimeLinePanel添加「Children」(或者您正在覆蓋面板的可視化樹並在「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),這也是對這種行爲的一些細節,這可以幫助你理解爲什麼是這樣。

+0

Thx很多。現在它可以工作。並感謝您的文章鏈接。 – drvj 2009-09-29 16:00:43

+0

好的,我碰到了同樣的問題,+1。 – 2014-04-28 13:38:40