【问题标题】:Error updating a UI bound collection in View Model from a different thread in the ViewModel从 ViewModel 中的不同线程更新 View Model 中的 UI 绑定集合时出错
【发布时间】:2012-12-02 07:56:34
【问题描述】:

我是 WPF、MVVM 和 MVVMLight 的菜鸟,请您帮我解决一些对我的项目非常重要的问题。我需要从视图模型创建的不同线程更新视图中的集合。我的 ViewModel 完全不知道 View。我在我的视图模型中定义了一个可观察的集合:

public class LoginViewModel: ViewModelBase
{
    public ObservableCollection<DatabaseConfiguration> DatabaseConfigurations{ get; set; }

    private DatabaseConfiguration _dbConfig;

    public DatabaseConfiguration DbConfig
    {
        get{return _dbConfig;}
        set
        {
        _dbConfig=value;
        RaisePropertyChanged(()=>DbConfig);
        }
    }

我使用 System.threading.Task 回调将一个项目从视图模型添加到集合中:

    void AddDBConfig(DatabaseConfiguration config)
    {
        Task<bool> asyncTask = Task.Factory.StartNew<bool>(
        () =>
        {
        return DatabaseUtility.ValidateDatabaseConnectionConfiguration(config);
        });        

        ExecuteAsync(asyncTask,
            (IAsyncResult ar) =>
            {
                Task<bool> t1 = (Task<bool>)ar;
                if (!t1.IsFaulted)
                {
                    if (!(bool)result)
                    {
                    //problematic statement
                    DatabaseConfigurations.Add(config);
                    }                    
                }
            }); 
    }

    public void ExecuteAsync(Task<object> asyncTask, AsyncCallback callback)
    {
        asyncTask.ContinueWith(task => callback(asyncTask));
        asyncTask.Start();
    }        
}

执行时出现以下错误:

“这种类型的 CollectionView 不支持从不同于 Dispatcher 线程的线程更改其 SourceCollection”

MVVMLight 工具包中是否有任何解决方法或内置机制来从不同的线程更新 UI 集合?

您的帮助将是一个很大的帮助!!! 谢谢!

【问题讨论】:

    标签: c# wpf mvvm task-parallel-library mvvm-light


    【解决方案1】:

    ContinueWith() 有一个接受 TaskScheduler 的重载。 wpf 和 winforms 有特殊的调度程序。您可以拨打TaskScheduler.FromCurrentSynchronizationContext()获取它

    请阅读here。

    SalientBrain 的回答也是正确的。

    【讨论】:

      【解决方案2】:
      Deployment.Current.Dispatcher.BeginInvoke(() =>
      {
          //(non)problematic statement
          DatabaseConfigurations.Add(config);
          //or perform creating of ObservableCollection
      });
      

      【讨论】:

      • 感谢您的回复。您能否告诉我在哪个程序集/命名空间中可以找到 Deployment.Current.Dispatcher()?在 System.Windows 中?还是 System.Deployment?后者没有定义“当前”属性,我猜
      • 感谢您的回复。您能否告诉我在哪个程序集/命名空间中可以找到 Deployment.Current.Dispatcher()?在 System.Windows 中?还是 System.Deployment?我猜后者没有定义“当前”属性。我的是一个 WPF MVVM 应用程序,.net 4.5,MVVMLight Extras V 4.1
      • @voroninp:谢谢。尝试调用 Dispatcher.beginInvoke() 时出现编译器错误。它说,非静态方法需要对象引用......该怎么办......?!!
      • @Ananth 使用静态属性 Dispatcher.Currant
      【解决方案3】:

      Mvvm light 有一个调度助手类来处理这个问题。见Simple example of DispatcherHelper。

      首先,在视图模型构造函数中初始化 DispatcherHelper。

      DispatcherHelper.Initialize(); 
      

      然后,使用 CheckBeginInvokeOnUI 从 ui 线程运行。

      DispatcherHelper.CheckBeginInvokeOnUI(
          () => DatabaseConfigurations.Add(config)
      );
      

      请注意,使用 mvvm light,属性更新会自动在 ui 线程上运行。只有集合需要调度程序帮助器方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-05
        • 1970-01-01
        • 2014-05-11
        • 2011-08-22
        • 2010-10-18
        • 2021-04-29
        • 1970-01-01
        相关资源
        最近更新 更多