views:

341

answers:

1

Hello, 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>

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:

VisualTree of ItemsPanelTemplate must be a single element.

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.

Thanks in advance.

+2  A: 

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.

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>

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.

Ugur Turan
Thx a lot. Now it works. And thank you for the link to the article.
drvj