smatter
smatter

Reputation: 29228

Getting Actual Size of UserControl before rendering

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

Upvotes: 6

Views: 1944

Answers (3)

Evert
Evert

Reputation: 21

See https://msdn.microsoft.com/en-us/library/6xe5hazb(v=vs.110).aspx The parameter "byval e as PaintEventArgs" in the example is not needed. In order to only retrieve the size needed to show the whole string, you can create your own paintEventArgs field in the subroutine MeasureStringMin.

Upvotes: 0

terphi
terphi

Reputation: 781

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.

Upvotes: 1

Stone
Stone

Reputation: 235

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.

Upvotes: 6

Related Questions