WPF/Multithreading: UI Dispatcher in MVVM

前端 未结 7 1371
有刺的猬
有刺的猬 2020-12-24 09:49

So say in an MVVM environment, I\'m in a background thread and I\'d like to run an update on a ui control. So normally I\'d go myButton.Dispatcher.BeginInvoke(blabla) but I

7条回答
  •  情深已故
    2020-12-24 09:59

    I tend to have my ViewModels inherit from DependencyObject and ensure that they are constructed on the UI thread, which poises them perfectly to handle this situation - they have a Dispatcher property that corresponds to the UI thread's dispatcher. Then, you don't need to pollute your view with the ViewModel's implementation details.

    Some other pluses:

    • Unit testability: you can unit test these without a running application (rather than relying on Application.Current.Dispatcher)
    • Loose coupling between View & ViewModel
    • You can define dependency properties on your ViewModel and write no code to update the view as those properties change.

提交回复
热议问题