开发者

Firing an Event from a Timer to WPF UI

I ha开发者_如何转开发ve an application that consists of a WPF UI with an "infrastructure" layer below it that has some references to various services with data. I've got a class, Updater, that has a couple properties that represent the data to be consumed by the UI layer. This updater has a Systems.Timer function such that every minute or so, it makes synchronous calls to the service and updates those aforementioned properties with a "refresh" of the data.

I'd like to raise an event from this class that the UI can be notified of the changes when it completes. When i did something akin to this previously, it was throwing exceptions right and left because the thread that fired the event was different (because it came from the timer elapsed event) then the thread the object was created on.

The crappy solution i'm using right now is to have another timer on the UI layer but...yuck.

What's the best way to notify the UI that the Updater class is all done with it's work?


Those cross-thread exceptions can be solved by updating the UI through the Dispatcher.Invoke function. The Dispatcher is an object that can be used to call onto the UI thread. Give this article a thorough read and you should be all set.


The best way to do this is through binding if you're able. Implement the System.ComponentModel.INotifyPropertyChanged interface with your data classes and then bind your UI elements to the properties of these classes that you want to display. When the properties are updated, they fire a PropertyChanged event, which is handled internally by WPF dependency objects and updates your UI automatically. This is a way to avoid a lot of the plumbing that you would normally have to put together yourself to respond to updates.

This blog entry gives a nice example of how to use it, but there are many many more available online.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜