WPF:访问绑定的ObservableCollection失败Althouth Dispatcher.BeginInvoke被使用 [英] WPF: Accessing bound ObservableCollection fails althouth Dispatcher.BeginInvoke is used

查看:185
本文介绍了WPF:访问绑定的ObservableCollection失败Althouth Dispatcher.BeginInvoke被使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

public ICollectionView Children
{
 get
 {
  // Determining if the object has children may be time-consuming because of network timeouts.
  // Put that in a separate thread and only show the expander (+ sign) if and when children were found
  ThreadPool.QueueUserWorkItem(delegate 
  {
   if (_objectBase.HasChildren)
   {
    // We cannot add to a bound variable in a non-UI thread. Queue the add operation up in the UI dispatcher.
    // Only add if count is (still!) zero.
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
     if (_children.Count == 0)
     {
      _children.Add(DummyChild);
      HasDummyChild = true;
     }
    }),
    System.Windows.Threading.DispatcherPriority.DataBind);
   }
  });

  return _childrenView; 
 }
}

效果很好:HasChildren在后台线程中运行,该线程使用分派器将其结果插入用于绑定到UI的变量中.

It works great: HasChildren is run in a background thread which uses the dispatcher to insert its result into the variable used for the binding to the UI.

注意:_childrenView设置为此:

Note: _childrenView is set to this:

_childrenView = (ListCollectionView) CollectionViewSource.GetDefaultView(_children);

问题:

如果我从另一个ThreadPool线程调用Children属性,则在该行中收到NotSupportedException

If I call the Children property from another ThreadPool thread, I get a NotSupportedException in the line

_children.Add(DummyChild);

异常文本:此CollectionView类型不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改."

Exception text: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

为什么??我已经验证了该代码是从Dispatcher线程执行的.

Why? I have verified that that code is executed from the Dispatcher thread.

推荐答案

我们自己遇到了这个问题.问题是双重的:

We've run into this problem before ourselves. The issue is twofold:

1-确保对SourceCollection所做的任何更改都在主线程上(您已经完成了).

1- Make sure that any changes to the SourceCollection are on the main thread (you've done that).

2-确保CollectionView的创建也在主线程上(如果是在其他线程上创建的,例如响应事件处理程序,通常不会这样). CollectionView希望修改是在其"线程上进行的,并且其"线程是"UI"线程.

2- Make sure that the creation of the CollectionView was also on the main thread (if it were created on a different thread, say in response to an event handler, this will not usually be the case). The CollectionView expects modifications to be on "its" thread, AND that "its" thread is the "UI" thread.

这篇关于WPF:访问绑定的ObservableCollection失败Althouth Dispatcher.BeginInvoke被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆