Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to data bind nested ListView ItemTemplates in Metro/WinRT?

In my ViewModel I have a collection of objects which each contain another collection. I am trying to display this in my View by using nested ListView ItemTemplates. Here is a simplification of my ViewModel code:

public ViewModelObject
{
    public ObservableCollection<OuterObject> OuterCollection { get; }
}

public OuterObject
{
    public string OuterTitle;
    public ObservableCollection<InnerObject> InnerCollection { get; }
}

public InnerObject
{
    public string InnerTitle;
}

And here is a simplification of how I'm trying to use this ViewModel in my XAML:

<ListView ItemsSource="{Binding OuterCollection}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding OuterTitle}"/>
                <ListView ItemsSource="{Binding InnerCollection}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding InnerTitle}"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

If I remove the inner ListView, the outer ListView binding works perfectly fine. I just can't figure out how to properly bind the inner collection object to the inner ListView. I've tried doing the inner binding with {Binding OuterCollection.InnerCollection}, {Binding DataContext.InnerCollection}, and {Binding RelativeSource={RelativeSource TemplatedParent}, Path=InnerCollection}, but all of these cause it to crash. What is the proper way to achieve this nested binding?

EDIT: I should add that this is for an application being ported from Windows Phone 7, and it is an attempt to find a replacement for LongListSelector, which is not available in WinRT.

like image 501
jokeefe Avatar asked Jul 13 '12 22:07

jokeefe


1 Answers

I figured out the solution! It required a combination of my previously attempted solutions. The correct binding for the internal collection in a nested ListView is:

{Binding RelativeSource={RelativeSource TemplatedParent},
                         Path=DataContext.InnerCollection}

Also, depending on your purpose for the nested ListViews, I found it better to use an ItemsView for the outer collection and a ListView for the inner collection. Otherwise, the selectability of the two controls overlap each other.

like image 122
jokeefe Avatar answered Nov 20 '22 20:11

jokeefe