Luke Puplett
Luke Puplett

Reputation: 45243

CollectionViewSource "Value does not fall within the expected range."

Why does this code produce the error in a Windows 8 XAML application?

Value does not fall within the expected range.

The XAML:

    <SemanticZoom>
        <SemanticZoom.ZoomedInView>
            <ListView
                Style="{StaticResource HorizontalListViewStyle}"
                SelectionMode="None"
                ScrollViewer.IsHorizontalScrollChainingEnabled="False"
                ItemsSource="{Binding BoardItems}" 
                ItemContainerStyle="{StaticResource ZoomedOutListViewItemContainerStyle}"
...

The MVVM code:

ObservableCollection<WritingBoardModel> boards = new ObservableCollection<WritingBoardModel>();

... // Add item models to boards.

CollectionViewSource v = new CollectionViewSource()
{
    Source = boards,
};

this.ViewModel.Add(BoardItemsViewModelKey, v);

If I skip the CollectionViewSource and directly add the boards instance to my view model, then it all works.

I think I need to use a CollectionViewSource in order to get some semantic zoom selection behaviour to work.

Upvotes: 5

Views: 4719

Answers (3)

Nate Diamond
Nate Diamond

Reputation: 5575

So, CollectionViewSources are weird and the way you have to bind to them is weird as well. To give you an example, in order to do it 'by the book' (the way the sample projects do), I've found it practically has to be a StaticResource as such:

<Page.Resource>
    <CollectionViewSource Source="{Binding Whatev}"
                          x:Key="WhatevSource"/>
</Page.Resource>

<GridView ItemsSource="{Binding Source={StaticResource WhatevSource}}"/>

Notice that we're not setting the source directly to the CollectionViewSource, but we're setting a 'pathless' Binding, basically using the CollectionViewSource as a DataContext (just one way to think of it, not actually technically correct).

This is the only way I've been able to get it to work, though I believe you can technically in the codebehind set the ItemsSource directly to the View of the CollectionViewSource or something similar.

Upvotes: 5

Shehab Fawzy
Shehab Fawzy

Reputation: 7828

In your Listview add "StaticResource" and "Source"

<ListView ItemsSource="{Binding Source={StaticResource WhatevSource}}"/>

Upvotes: 2

Luke Puplett
Luke Puplett

Reputation: 45243

I needed to bind to the View property of the CollectionViewSource like this:

CollectionViewSource v = new CollectionViewSource()
        {
            IsSourceGrouped = false,
            Source = boards,
        };

this.ViewModel.Add(BoardItemsViewModelKey, v.View);

Mind you, this doesn't help with my two ListViews and keeping them in selection synch in a SemanticZoom.

Upvotes: 0

Related Questions