2016-06-19 32 views
3

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

... 
     <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:(代码隐藏创建CollectionViewSource W/O过滤)无记录在数据网格):

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

你提高的PropertyChanged财产DataItems? –

+0

哦!我认为CollectionViewSource实现自动RaisePropertyChanged(作为ObservableCollection)。 不好意思! – user1576474

+0

当然可以,但是您要更改DataItems属性,并且必须通知该更改。 CVS不知道你分配了哪个属性 - 所以它本身不能通知这个; o) –

回答

1

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

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

确保您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 
    } 
... 
+2

如果你想摆脱这种样板使用https://www.nuget.org/packages/PropertyChanged.Fody/ –

+0

@ SirRufo,感谢您的信息 – omerts