简体   繁体   中英

Interoperability between System.Windows.Forms.Application and System.Windows.Application

I have to integrate a WPF UI into a .NET 2.0 application.

ObservableCollection needs to be modified in the GUI Dispatcher thread, so I came up with a solution involving 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);
}

However, since the project was originally written with .NET 2.0, the main thread uses a System.Windows.Forms.Application , so System.Windows.Application.Current is null.

I can't just replace the current System.Windows.Forms.Application with a System.Windows.Application since my application heavily relies on this API and the two classes are widely incompatibles.

Is there a way to get the current System.Windows.Application ? Or a way to call BeginInvoke() on my System.Windows.Forms.Application ? Or am I deemed to write my own DIY system to delegate edition of the collection from the correct thread ?

You should save a reference to SynchronizationContext.Current from the UI thread (perhaps in a static property) and use it instead of the Dispatcher .

In WPF, this will return a DispatcherSynchronizationContext ; in WinForms, it will return a WindowsFormsSynchronizationContext .

You can then call Post on the saved SynchronizationContext , which is equivalent to BeginInvoke .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM