views:

461

answers:

2

The CollectionViewSource.GetDefaultView() method is not in Silverlight 3. In WPF I have this extension method:

public static void SetActiveViewModel<ViewModelType>(this ViewModelBase viewModel,
    ViewModelType collectionItem,
    ObservableCollection<ViewModelType> collection) where ViewModelType : ViewModelBase
{
    Debug.Assert(collection.Contains(collectionItem));
    ICollectionView collectionView = CollectionViewSource.GetDefaultView(collection);
    if(collectionView != null) collectionView.MoveCurrentTo(collectionItem);
}

How can this be written in Silverlight 3?

A: 

One thing that you might be able to do is to manually create the CollectionViewSource, set its Source property to the collection, then get the CollectionView using the View property of the CollectionViewSource.

Something like this might work:

public static void SetActiveViewModel<ViewModelType>(this ViewModelBase viewModel,
    ViewModelType collectionItem,
    ObservableCollection<ViewModelType> collection) where ViewModelType : ViewModelBase
{
    Debug.Assert(collection.Contains(collectionItem));
    CollectionViewSource collectionViewSource = new CollectionViewSource();
    collectionViewSource.Source = collection;
    ICollectionView collectionView = collectionViewSource.View;
    if(collectionView != null) collectionView.MoveCurrentTo(collectionItem);
}
Waleed Al-Balooshi
This doesn't work. Since you've created a new instance of CollectionViewSource you will get a View to which nothing is bound. Hence MoveCurrentTo affects nothing. In WPF controls that bind to collections will actually bind to a default view for that collection, the original code acquires that default view and manipulates it thereby affecting anything bound to it.
AnthonyWJones
+1  A: 

Silverlight does not contain the concept of a Default view. When you ask a control in Silverlight to bind to a collection it really does bind to the collection, it does not bind to a default view.

As result I don't think there can be a direct and complete port of your extension method. Some re-engineering of your MVVM implementation will be needed. I've not come across the concept of a collection of view model instances before so I'm not exactly sure what would be appropriate in your case.

A couple of approaches I've seen with CollectionViewSource is to either have the CollectionViewSource defined in the Xaml and bind its Source to something in the ViewModel. Alternatively have a ViewModel expose a CollectionViewSource property and have the View xaml bind to its View proeprty.

AnthonyWJones