4

I've a CollectionViewSource as ItemsSource of my DataGrid. In Window.Resources I have this definition:

<CollectionViewSource x:Key="ItemsPoolCollectionView"  
     Source="{Binding Path=MyObservableCollection, Mode=OneWay}" />

now, I would like to produce the same definition from code, so I've done this:

Dim _cvs as CollectionViewSource = New CollectionViewSource
Dim bindSource = New Binding() With {
        .Path = New PropertyPath("MyObservableCollection"),
        .Mode = BindingMode.OneWay }
_cvs.SetValue(CollectionViewSource.SourceProperty, bindSource)

but I've this error on the last statement:

'System.Windows.Data.Binding' is not a valid value for property 'Source'

What's wrong? How can I accomplish this?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Luca Petrini
  • 1,695
  • 2
  • 28
  • 53

2 Answers2

4

I solve! ...in this way:

      Dim _cvs as CollectionViewSource = New CollectionViewSource
      Dim bindSource = New Binding() With {
              .Source = Me.DataContext
              .Path = New PropertyPath("MyObservableCollection"),
              .Mode = BindingMode.OneWay }
      BindingOperations.SetBinding(cvs, CollectionViewSource.SourceProperty, bindSource)
Luca Petrini
  • 1,695
  • 2
  • 28
  • 53
1

You don't need to bind a CollectionViewSource in order to make it "bind" automatically; just set the value of the Source property directly:

Dim _cvs as CollectionViewSource = New CollectionViewSource
_cvs.Source = Me.MyObservableCollection

(sorry for my rusty VB.net)

For more info, see the following forum post: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f44df11b-dfa8-4173-bbc8-051875fce4cc

robertos
  • 1,810
  • 10
  • 12
  • I try and it works...but if I change "MyObservebleCollection" on datacontext (clear, add or remove items) the collectionviewsource seems lost the source association. – Luca Petrini Oct 27 '10 at 09:55