views:

153

answers:

1

Hi there, I'm using a ListView to show Items in a List. The user can select the items himself, or use some 'preselect keys' to select items with specified attributes.

To check the items I use something like that:

for(int i;i<MyListView.Items.Count;++i)
{
    if( /*... Check if the items should be selected ...*/ )
        (MyListView.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem).IsSelected = true;
}

This works perfectly for items, that are visible at the time of excecution. But for items, that are not visible, ContainerFromIndex() returns null. I heard this has something to do with virtualization, and that the List doesn't know about items upside or downside the 'field of view'. But how comes that it is possible to have selected items in the List offside the 'field of view' when you select them manually?

And how to do a select of an item outside 'field of view'? I think that must be possible.

Thanks for any help, Marks

+1  A: 

As you mentioned, my guess is that the problem is virtualization of the ListView items. By default, ListView (and ListBox) use VirtualizingStackPanel as their ItemsPanel to improve performance. A brief explanation for how it works can be read here.

You can substitute another Panel, however. In this case, try using a normal StackPanel. If you have a ton of items in the ListView, especially if they are complex items, performance might suffer a little.

<ListView>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

Edit

You can also try to solution described at this similar question, depending on your model. However, this probably won't work for you.

Benny Jobigan
But how can it then be, that when I select an item, scroll it out of sight and scroll back, that it is still selected? Somewhere this information must be stored. Is this really not accessable?
Marks
Well, the selected items are accessable via `SelectedItems`. It returns an IList, which has an Add() method. Did you try adding items you want selected to that list? That means you have to add items to this IList from whatever collection you're showing in the ListView. There might not be a way to do it using the indexes only.
Benny Jobigan