【问题标题】:ObservableCollection is not updating dataObservableCollection 没有更新数据
【发布时间】:2013-10-03 13:27:16
【问题描述】:

我遇到了 observablecollection 的问题,因为它没有更新我的视图。它正在获取数据,我已经检查过了。我也将事件设置为它的集合更改事件,但它也没有被调用。我不知道为什么会发生这种情况是我的代码..

public async Task GetActivityStudentCollection()
    {

        StudentActivityCollection =  await ViewModelLocator.ActivityViewModel.GetActivity(0, 8, 0, 20);

        StudentActivityCollection.CollectionChanged += StudentActivityCollection_CollectionChanged;
   //     RaisePropertyChanged("StudentActivityCollection");
    }

    void StudentActivityCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
      //  throw new NotImplementedException();
    }

我已经将这个集合与这样的列表视图绑定了。

 ActivityListViewSource.Source = ViewModelLocator.DashBoard.StudentActivityCollection;

这个 ViewModelLocator.ActivityViewModel.GetActivity(0, 8, 0, 20); 方法返回一个我已经绑定的集合(不工作)但是如果我将集合直接绑定到集合这将是返回它的工作..意味着如果我像这样绑定(它工作)..

ActivityListViewSource.Source = ViewModelLocator.ActivityViewModel.ActivityCollection;

我很抱歉我的英语不好。请尝试理解问题。 是因为异步方法还是什么。任何形式的帮助表示赞赏..

【问题讨论】:

  • 您是否尝试过遍历“ViewModelLocator.ActivityViewModel.ActivityCollection”并将每个对象添加到“StudentActivityCollection”?
  • no samar 实际上我已经得到了整个集合并且只是将它复制到绑定集合..因为如果假设如果集合太大那么它是不可行的..
  • 只是为了测试目的尝试一下。看看这是否有效。我们以后可以想出更好的方法。
  • @samar 它正在工作..没有它有什么办法吗..
  • 更新我会正确标记的答案。它的工作方式是“var asd = await ViewModelLocator.ActivityViewModel.GetActivity(0, 8, 0, 20); foreach (var item in asd ) { StudentActivityCollection.Add(item); }"

标签: c# .net data-binding observablecollection async-await


【解决方案1】:

试试这样的

public async Task GetActivityStudentCollection()
{

    var studentActivityColl =  await ViewModelLocator.ActivityViewModel.GetActivity(0, 8, 0, 20);

    foreach(var studentAct in studentActivityColl)
        StudentActivityCollection.Add(studentAct);

    StudentActivityCollection.CollectionChanged += StudentActivityCollection_CollectionChanged;
//     RaisePropertyChanged("StudentActivityCollection");
}

【讨论】:

  • samar,请您在不逐项添加的情况下解决问题
  • 我不确定这是否可行,但尝试为包含“StudentActivityCollection”的模型实现 INotifyPropertyChanged 接口,并在“StudentActivityCollection”集合内调用 PropertyChanged 事件。然后尝试您的原始代码。这里给出了一个完整的实现。试试看,让我知道它是否有效。 stackoverflow.com/questions/14783750/…
【解决方案2】:

您不应该从该方法返回新集合。你应该传递一个实例。

ObservableCollection studentActivityCollection = new ObservableCollection();

studentActivityCollection.CollectionChanged += StudentActivityCollection_CollectionChanged;

await ViewModelLocator.ActivityViewModel.GetActivity(studentActivityCollection, 0, 8, 0, 20);

因为所有事件都在您注册事件之前触发。

【讨论】:

  • jeroen 触发此事件不是问题。实际上它没有更新数据。意味着它只是我已申请的一项检查,顺便说一句它不起作用..感谢您的努力...请尝试了解问题
  • 我认为StudentActivityCollection = await ViewModelLocator.ActivityViewModel.GetActivity(0, 8, 0, 20); 会覆盖旧集合。它应该添加项目,而不是返回一个新集合。
猜你喜欢
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多