CollectionViewSource代码隐藏绑定MVVM

时间:2016-06-19 08:30:03

标签: c# wpf mvvm datagrid collectionviewsource

我有MainWindow.xaml(View)和MainWindowViewModel.cs(ViewModel)。 在我的程序中,我在 Worklist.Result(observablecollection)中启动了异步加载数据的自定义类。此时我需要使用自定义过滤数据。如果我在xaml中创建CollectionViewSource都完美显示但我无法将Filter事件绑定到CollectionViewSource。好的,那么我需要代码隐藏的CollectionView ......但最终DataGrid不显示数据(没有绑定错误,CollectionViewSource有所有记录)。为什么? 示例1 :( XAML创建的CollectionViewSource没有过滤)一切正常!
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>

示例2:(CodeBehind创建的CollectionViewSource没有过滤)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);

        }

然后,WorkList_PropertyChanged事件引发了CollectionViewSource中的所有数据,但未引发DataGrid中的所有数据。有人可以帮助解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

为了让WPF引擎知道DataItems已更新为新值, 您的DataItems需要通知PropertyChanged

即使CollectionViewSource.GetDefaultView(WorkList.Result);的结果是ObservableCollection,视图也不知道它,因为没有DataItems已更新的通知。

确保您的MainWindowViewModel实现了INotifyPropertyChanged,您可以这样做:

...
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
  }
...
相关问题