views:

38

answers:

1

Hello,

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 ?

+1  A: 

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.

SLaks