System.Windows.Forms.Application和System.Windows.Application之间的互操作性

sla*_*ppy 5 .net c# interop

我必须将WPF UI集成到.NET 2.0应用程序中.

需要在GUI Dispatcher线程中修改ObservableCollection,因此我提出了一个涉及的解决方案 InvokeLater()

ObservableCollection<Item> items;
public delegate void AddItemDelegate(Item i);

public void AddItem(Item item)
{
    System.Windows.Application.Current.Dispatcher.BeginInvoke(
        new AddItemsDelegate(i => items.Add(i), item);
}
Run Code Online (Sandbox Code Playgroud)

但是,由于该项目最初是使用.NET 2.0编写的System.Windows.Forms.Application,因此主线程使用a ,因此System.Windows.Application.Current为null.

我不能只System.Windows.Forms.Application用一个替换当前的System.Windows.Application应用程序,因为我的应用程序严重依赖于这个API,这两个类是广泛不兼容的.

有没有办法获得当前的System.Windows.Application?还是一种打电话BeginInvoke()给我的方式System.Windows.Forms.Application?或者我是否考虑编写自己的DIY系统来从正确的线程委托该集合的版本?

SLa*_*aks 5

您应该SynchronizationContext.Current从UI线程(可能在静态属性中)保存引用,并使用它代替Dispatcher.

在WPF中,这将返回一个DispatcherSynchronizationContext; 在WinForms中,它将返回一个WindowsFormsSynchronizationContext.

然后你可以调用Post已保存的SynchronizationContext,相当于BeginInvoke.