CollectionViewSource.GetDefaultView is not in Silverlight 3! What's the work-around?

折月煮酒 提交于 2019-12-10 16:50:10

问题


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?


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/2530942/collectionviewsource-getdefaultview-is-not-in-silverlight-3-whats-the-work-aro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!