首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CollectionViewSource代码隐藏绑定MVVM的奇怪行为

CollectionViewSource代码隐藏绑定MVVM的奇怪行为
EN

Stack Overflow用户
提问于 2016-06-19 08:30:02
回答 1查看 598关注 0票数 3

我有MainWindow.xaml (视图)和MainWindowViewModel.cs (ViewModel)。在我的程序中,我有一个自定义类,用于在Worklist.Result中启动时加载数据。此时,我需要使用自定义过滤数据。如果我在xaml中创建CollectionViewSource,所有的显示都很完美,但是我不能将Filter事件绑定到CollectionViewSource。好吧,那我需要代码背后的CollectionView.但最后,DataGrid不显示数据(没有绑定错误,CollectionViewSource拥有所有记录)。为什么?示例1:(XAML创建的CollectionViewSource w/o过滤)一切正常!

MainWindow.xaml

代码语言:javascript
复制
...
        <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 w/o过滤)DataGrid!中没有记录):

MainWindow.xaml

代码语言:javascript
复制
<xdg:DataGridControl VerticalAlignment="Stretch" Background="White" ItemsSource="{Binding DataItems}" ... </xdg:DataGridControl>

MainWindowViewModel.cs

代码语言:javascript
复制
...
public ICollectionView DataItems { get; private set; }
...
private void WorkList_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
                DataItems = CollectionViewSource.GetDefaultView(WorkList.Result);

        }

然后,WorkList_PropertyChanged事件将在CollectionViewSource中引发所有数据,而在DataGrid中则不会。有人能帮忙解决这个问题吗?

EN

Stack Overflow用户

回答已采纳

发布于 2016-06-19 09:30:17

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

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

确保您的MainWindowViewModel,实现了INotifyPropertyChanged,并且您可以:

代码语言:javascript
复制
...
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
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37905339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档