user1576474
user1576474

Reputation: 674

Strange behavior of CollectionViewSource code-behind binding MVVM

I have MainWindow.xaml (View) and MainWindowViewModel.cs (ViewModel). In my program i have custom class for async loading data at startup in Worklist.Result (observablecollection). At this moment i need use custom filtering data. If i create CollectionViewSource in xaml all display perfectly but i can't bind Filter event to CollectionViewSource. Ok, then i need code-behind CollectionView... But finally DataGrid doesn't display data (no bindings error, CollectionViewSource have all records). Why? Example 1: (XAML-created CollectionViewSource w/o filtering) All is OK!
MainWindow.xaml

...
        <xdg:DataGridCollectionViewSource x:Key="DataItems"
                                Source="{Binding WorkList.Result}" 
        <xdg:DataGridCollectionViewSource.GroupDescriptions>
            <xdg:DataGridGroupDescription PropertyName="Date"/>
        </xdg:DataGridCollectionViewSource.GroupDescriptions>
    </xdg:DataGridCollectionViewSource>-->
...
  <xdg:DataGridControl VerticalAlignment="Stretch" Background="White" ItemsSource="{Binding Source={StaticResource DataItems}}" ... </xdg:DataGridControl>

Example 2: (CodeBehind-created CollectionViewSource w/o filtering) NO RECORDS in DataGrid!):

MainWindow.xaml

<xdg:DataGridControl VerticalAlignment="Stretch" Background="White" ItemsSource="{Binding DataItems}" ... </xdg:DataGridControl>

MainWindowViewModel.cs

...
public ICollectionView DataItems { get; private set; }
...
private void WorkList_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
                DataItems = CollectionViewSource.GetDefaultView(WorkList.Result);

        }

Then WorkList_PropertyChanged event was raised all data in CollectionViewSource but not in DataGrid. Can someone help with this problem?

Upvotes: 3

Views: 667

Answers (1)

omerts
omerts

Reputation: 8838

In order for the WPF engine to know that DataItems have updated with a new value, your DataItems need to notify of PropertyChanged.

Even if the result of CollectionViewSource.GetDefaultView(WorkList.Result);, is an ObservableCollection, the view doesn't know it, since there is no notification that DataItems have updated.

Make sure your MainWindowViewModel, implements INotifyPropertyChanged, and you can do:

...
private ICollectionView _dataItems;
public ICollectionView DataItems { 
  get
  {
    return this._dataItems;
  }
  private set 
  {
    this._dataItems = value;
    this.OnPropertyChanged("DataItems"); // Update the method name to whatever you have
  }
...

Upvotes: 2

Related Questions