views:

445

answers:

2

I am trying to access a List on a view model from a background worker, but am getting errors because I am going cross thread...

This is the problem method on the viewmodel: (I am getting the exception the first line in the function (SMMainWindow window ...))

public static MainWindowViewModel GetMainWindowViewModel() {
            SMMainWindow window = (SMMainWindow)System.Windows.Application.Current.MainWindow;
            if (window != null) {
                return (MainWindowViewModel)window.DataContext;
            }
            return null;
}

Any ideas? Sample code would be appreciated

+3  A: 

It helps tremendously if you setup your ViewModel with an instance of your Window's Dispatcher. If you have this, then you can just use Dispatcher.Invoke to fetch or set items within the ViewModel.

Reed Copsey
I'm sorry, I am a bit of a dispatcher noob... how would I get an object from the viewmodel with that? I thought it was the window's dispatcher and not the viewmodel?
jle
I figured it out... had to add a method to get it... dispatcher worked well
jle
A: 

If it's Freezable, you might be able to freeze your window. This should allow you to access it.

The dispatcher approach is probably a good option, but I always feel like this is a violation (feels like the ViewModel dealing with the UI too closely), but it's probably personal preference.

I question your approach here, however. Is there a good reason one ViewModel is trying to reference another? I'd consider rethinking this approach... Generally when people do this they are accessing ViewModel when really they should be touching the Model instead.

Anderson Imes