【问题标题】:wpf notsupportedexceptionwpf 不支持异常
【发布时间】:2012-04-06 20:56:21
【问题描述】:

我有一个 mvvm 应用程序,

在视图模型中:

    public CommandViewModel()         
    {
        Messenger.Default.Register<CustomerSavedMessage>(this, message =>
        {
            Customers.Add(message.UpdatedCustomer);
        });
    } 

    private ObservableCollection<Customer> _customers;
    public ObservableCollection<Customer> Customers 
    {
        get { return _customers; }
        set
        {
            _customers = value;
            OnPropertyChanged("Customers");
        }
    }

在我看来,客户被绑定到一个组合框。

在不同的视图模型中,我在不同的线程上提出了 CustomerSavedMessage 当我尝试在上面的注册处理程序委托中处理消息时 抛出一个不支持的异常并显示以下消息:

   {"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."}

我显然需要使用Dispatcher对象进行跨线程操作, 但我无法从视图模型中弄清楚这是如何完成的。

我还认为框架会知道如何处理过度绑定之间的交叉线程..

如何在 Dispatcher 线程上执行 Customers.Add(message.UpdatedCustomer) ?

【问题讨论】:

    标签: c# wpf dispatcher


    【解决方案1】:

    您可以使用Application.Current.Dispatcher 为应用程序的主线程获取Dispatcher 或在ViewModel 构造函数中捕获调度程序(Dispatcher.CurrentDispatcher)。

    例如:

    Messenger.Default.Register<CustomerSavedMessage>(this, message =>
    {
         Application.Current.Dispatcher.Invoke(
             new Action(() => Customers.Add(message.UpdatedCustomer))); 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多