Charles Petzold on writing books, reading books, and exercising the internal UTM

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

CompositionTarget.Rendering and RenderEventArgs

June 11, 2010
Roscoe, N.Y.

Sometimes it helps to read the .NET documentation even for a feature you think you know well. From WPF I knew about the CompositionTarget.Rendering event and I've also used it in Silverlight. The event is fired at the rate of video refresh and hence is ideal for performing animations. But just a couple days ago I re-read the documentation for the Silverlight version of the CompositionTarget.Rendering event and happened upon the following:

RenderingTime is of type TimeSpan and indicates the elapsed time since the application began running. Using these TimeSpan values to pace animations is probably better than assuming that successive firings of the Rendering event occur at exactly the video refresh rate. Because the Rendering event handler is called in the UI thread, it is likely not precisely regular.

This casting technique also works in WPF although I haven't been able to find documentation there. (And I have a nagging suspicion that I actually knew about this at one time.) It also works in Silverlight for Windows Phone 7.

Here's a Silverlight clock that is updated from the RenderingTime property in a CompositionTarget.Rendering handler:

Get Microsoft Silverlight

The clock begins when the Silverlight application begins. You can reset it by refreshing the page.

And here's the source code. The visuals are based on the notorious all-XAML clock in Chapter 30 of Applications = Code + Markup.


Good Post. Using RenderingTime is also more reliable if you need animations to progress even if the user switches tabs in the browser, since the Rendering event doesn't seem to fire then.

Phil M, Sun, 13 Jun 2010 19:19:18 -0400

Excellent point. — Charles

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold