【问题标题】:Strange behavior of CollectionViewSource code-behind binding MVVMCollectionViewSource 代码隐藏绑定 MVVM 的奇怪行为
【发布时间】:2016-10-20 16:40:37
【问题描述】:

我有 MainWindow.xaml (View) 和 MainWindowViewModel.cs (ViewModel)。 在我的程序中,我有自定义类,用于在 Worklist.Result (observablecollection) 中启动时异步加载数据。此时我需要使用自定义过滤数据。如果我在 xaml 中创建 CollectionViewSource 全部显示完美,但我无法将过滤器事件绑定到 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);

        }

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

【问题讨论】:

  • 您是否为属性 DataItems 提出了 PropertyChanged?
  • 哦!我认为 CollectionViewSource 实现自动 RaisePropertyChanged(作为 ObservableCollection)。打扰了!
  • 当然可以,但是您更改了 DataItems 属性并且您必须通知该更改。 CVS 不知道您分配给它的属性 - 所以它自己不能通知这个;o)

标签: c# wpf mvvm datagrid collectionviewsource


【解决方案1】:

为了让 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
  }
...

【讨论】:

猜你喜欢
  • 2011-03-08
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多