簡體   English   中英

WPF 在 UI 線程中更新 observableCollection

[英]WPF update observableCollection in UI thread

我有帶 WPF UserControl 的 WinForms。

public partial class DynamicMediator : Form
{
        public DynamicMediator()
        {
            InitializeComponent();
            lmDynamicMediator = new LMDynamicMediator.MediatorMainWindow();            
            this.elementHost1.Child = this.lmDynamicMediator;
        }
        public MainWindowViewModel GetEditFormViewModel()
        {
            return lmDynamicMediator.Resources["ViewModel"] as MainWindowViewModel;
        }
}

我在我的 ViewModel 中開始一個新進程之后我需要在我使用的 ViewModel 中更新我的 observableCollection

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => HasListMessages.Add(item)));

但我有這樣的例外

這種類型的 CollectionView 不支持從不同於 Dispatcher 線程的線程更改其 SourceCollection

如果我使用這樣的代碼

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => HasListMessages.Add(item)));

我有這樣的例外

System.Windows.Application.Current.get 返回 null

我做錯了什么?

如何在我的 ViwModel 中獲取 System.Windows.Application.Current

在尚未與 Dispatcher 關聯的線程中調用Dispatcher.CurrentDispatcher將創建一個新的 Dispatcher,它不是 UI 線程的 Dispatcher。

使用創建視圖 model 實例的線程的 Dispatcher。 保持在視野范圍內 model class

public class MainWindowViewModel
{
    private readonly Dispatcher dispatcher;

    public MainWindowViewModel()
    {
        dispatcher = Dispatcher.CurrentDispatcher;
    }

    ...
}

然后使用該字段:

dispatcher.BeginInvoke(() => HasListMessages.Add(item));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM