共用方式為


How do I get the height/width of a Silverlight UIElement if its not explicitly set?

The answer is, of course, to use the ActualHeight and ActualWidth properties. But wait, ActualHeight and ActualWidth return 0.0, what gives?  Well it turns out that if you just check the ActualHeight and ActualWidth right away, you are getting the measurements of the element BEFORE it has been measured and sized.  The way to accurately use the ActualHeight and ActualWidth properties is to first subscribe to the element’s SizeChanged event. 

 myElement.SizeChanged += new SizeChangedEventHandler(OnSizeChanged);

Now, in the event handler you can use the NewSize property to get the newly measured ActualHeight and ActualWidth.

 private void OnSizeChanged(object sender, 
                           SizeChangedEventArgs e)
{
    actualHeight = e.NewSize.Height;
    actualWidth = e.NewSize.Width;
}

Thanks everybody!  I’ll be here all week!  Be sure to tip your waitresses…

Comments

  • Anonymous
    September 15, 2013
    ActualHeight,ActualWidth Properties are read only, How can I Set the newSize to those Properties.