Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Actual Size of UserControl before rendering

Tags:

c#

silverlight

I am trying to get the ActualSize of MyUserControl before it gets rendered using Measure methode of UserControl class as suggested for my previous question. However it is not working. MyUserControl has an ItemsControl that is databound with a List as shown below. The items added through uc.MyCollection = myCollection; is not getting reflected in uc.DesiredSize.Height.

MyUserControl uc= new MyUserControl();
uc.AName = "a1";
uc.Width = 194;
uc.MyCollection = myCollection; //myCollection is  a List databound to ItemsControl inside MyUserControl
uc.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
uc.Arrange(new Rect(0, 0, uc.DesiredSize.Width, uc.DesiredSize.Width)); //Needed?
uc.UCHeight = uc.DesiredSize.Height; //size of items databound to ItemsControl not reflected here
uc.UCWidth = uc.DesiredSize.Width;
uc.Margin = new Thickness(34, 42, 0, 0);
myRoot.Children.Add(uc); //myRoot is Canvas
like image 594
softwarematter Avatar asked Dec 29 '11 08:12

softwarematter


2 Answers

You have to override MeasureOverride and ArrangeOverride in your uc to calculate the size for your own. Inside MeasureOverride "ask" your List with "Measure" of its own size - so you can calculate the size for your own uc (returning this size in MeasureOverride) - then you get your DesiredSize after calling uc.Measure.

like image 172
Stone Avatar answered Oct 14 '22 20:10

Stone


Your ItemsControl binding to MyCollection will not process until your user control is in the VisualTree, so at the point you call Measure, the desiredsize is still 0.

When I need to get the size of a FrameworkElement, I set it's Opacity to 0, add it to the visual tree, and wait for the SizeChanged event.

like image 27
terphi Avatar answered Oct 14 '22 18:10

terphi