0
votes

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

1
CollectionViewSource is intended to be used in XAML. You're looking for a CollectionView in the ViewModel. - Federico Berasategui
Why can you 'only find [a Static]resource from code-behind'? Surely the whole point of declaring a StaticResource is that you can then refer to it in XAML? - Sheridan
@Sheridan, i have two ui and two code-behind. how i can route event/command from one ui to another ui? most of sample code i see, code-behind is very light. - archlight
@HighCore, you are right. you can even get collectionview without declaring collectionviewsource in xaml or behind-code. there is default view for each collection object - archlight

1 Answers

3
votes

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.