简体   繁体   中英

wpf collectionviewsource in viewmodel or xaml code-behind

I am in this dilemma and hope someone can help me out

sorry I cannot paste code here as company block posting here.

i am trying to use collectionviewsource in xaml. i tried two ways, static resource and cvs.source. first one works pretty well but limitation is i can only find resource from code-behind. but control ui and disaplay ui not on same view, i don't know how to trigger sort/filter so i move to second option, i put cvs in view model with properties exposed to both ui. but i got this famous error "trying to change ui not owned by this thread"

so generally what is good practice of where to put csv. i checked many places suggesting second option http://www.xamlplayground.org/post/2009/07/18/Use-CollectionViewSource-effectively-in-MVVM-applications.aspx and XAML Binding to a CollectionViewSource property on a ViewModel but seems no one mentioned ui thread ownership issue. am I doing something really stupid

thanks

If you keep having problems with threads, use a Dispatcher :

Application.Current.Dispatcher.Invoke(
  new Action(() => /* modify the collection */));

Or use EnableCollectionSynchronization method, which is new in WPF 4.5 and will do the same for you:

private static object syncObject = new object();
//...
BindingOperations.EnableCollectionSynchronization(yourCollection, syncObject);

Read more about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM