0

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

Community
  • 1
  • 1
archlight
  • 687
  • 1
  • 6
  • 12
  • `CollectionViewSource` is intended to be used in XAML. You're looking for a `CollectionView` in the ViewModel. – Federico Berasategui Sep 13 '13 at 15:59
  • 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 Sep 13 '13 at 16:05
  • @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 Sep 13 '13 at 16:21
  • @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 Sep 19 '13 at 15:01

1 Answers1

3

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.

pbalaga
  • 2,018
  • 1
  • 21
  • 33
  • +1 for the coding example of EnableCollectionSynchronization. – Gayot Fow Sep 13 '13 at 16:22
  • thanks for suggestion, i will take a look at EnableCollectionSynchronization. but i don't like to introduce new technique each time i hit a problem as i believe this is very common usecase and I am newbie in wpf. just want to have basic right – archlight Sep 13 '13 at 16:24