1

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


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.

4

2 回答 2

3

如果您使用 Window 的 Dispatcher 实例设置 ViewModel,它将有很大帮助。如果你有这个,那么你可以使用 Dispatcher.Invoke 来获取或设置 ViewModel 中的项目。

于 2009-08-05T00:51:22.140 回答
0

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.

于 2009-08-05T03:03:53.247 回答