Saturday, July 12, 2008

Quick Silverlight tip: Why my ActualWidth and ActualHeight equal 0?

If you’ll try to use ActualWidth and ActualHight of controls with explicitly set Width and Height, you’ll not see any problem, however, if your control sits inside other control, ActualWidth and ActualHeight properties will be equal to 0. Why this and how to fix it?

Actually, measurement and layout pass in Silverlight run asynchronously, thus it executed with or, even after, your code. So in order to fix it, you should measure ActualWidth and Actual Height asynchronously. So, instead of:

//get and use ActualWidth/ActualHeight

Use:

Dispatcher.BeginInvoke(delegate
{
  //get and use ActualWidth/ActualHeight
});

It will allows you to detect actual size of your control.

Have a nice day and be good people.

1 comment:

toadslick said...

wooooo! thanks! this has been plaguing me for a day now.

gotta remember to think asynchronously. ^_^