开发者

Initiate change of a DependencyProperty of a ViewModel with a Event of another Thread

开发者 https://www.devze.com 2023-03-09 16:26 出处:网络
I want to change a DependencyProperty of my Vie开发者_如何学GowModel from a class which connects the application to a database.

I want to change a DependencyProperty of my Vie开发者_如何学GowModel from a class which connects the application to a database.

This class raises events which should initiate a change of some properties in my ViewModel.

How can I realize that? I don't have the Dispatcher of the View.


I'm assuming you don't really have dependency properties on your viewmodels but rather normal C# properties which raises the PropertyChanged event.

If so, you should be fine already. Modify your properties from your background thread (normal concurrency issues apply obviously) and when they are bound to a WPF element's Dependency Property the runtime system will take care of marshalling the change to the proper thread (by using the view's Dispatcher object)

This works for normal properties, I'm not sure it works for ObservableCollections.

There are also different approaches for doing the marshalling inside the viewmodels. The simplest way is to just store the value of Dispatcher.CurrentDispatcher in your viewmodel's constructor. This works as long as your viewmodels are created on the UI thread.


One immediate solution to the problem is to capture the view's Dispatcher and store it on the view model when you create it, so you can Invoke/BeginInvoke the change to it in response to the event.

That being said, you should consider making your viewmodels use INotifyPropertyChanged with CLR properties rather than DependencyProperties to avoid issues like this. That way, any thread can make changes to your viewmodel and have the results reflected in the view.

0

精彩评论

暂无评论...
验证码 换一张
取 消