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


4

2 に答える 2

3

Window の Dispatcher のインスタンスを使用して ViewModel をセットアップすると、非常に役立ちます。これがあれば、Dispatcher.Invoke を使用して ViewModel 内の項目を取得または設定できます。

于 2009-08-05T00:51:22.140 に答える
0

Freezable の場合、ウィンドウをフリーズできる可能性があります。これにより、アクセスできるようになります。

ディスパッチャーのアプローチはおそらく良い選択肢ですが、これは違反だと常に感じています (ViewModel が UI を密接に扱っているように感じます) が、おそらく個人的な好みです。

ただし、ここでのアプローチには疑問があります。ある ViewModel が別の ViewModel を参照しようとする正当な理由はありますか? 私はこのアプローチを再考することを検討します...一般的に、人々がこれを行うとき、実際には代わりにモデルに触れる必要があるときにViewModelにアクセスしています。

于 2009-08-05T03:03:53.247 に答える