Getting the actual size of a UserControl before rendering

I am trying to get ActualSize MyUserControl before getting the render using the Measure method of UserControl , as suggested for my previous question . However, it does not work. MyUserControl has an ItemsControl , which is a data binding with a List , as shown below. Elements added via uc.MyCollection = myCollection; are not 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 
+6
source share
3 answers

You need to override MeasureOverride and ArrangeOverride in your uc in order to calculate the size for your. Inside MeasureOverride, β€œask” your List with a β€œMeasure” of your own size - so you can calculate the size for your own uc (returning that size to MeasureOverride) - then you get your DesiredSize after calling uc.Measure.

+6
source

Your binding of the ItemsControl to MyCollection will not be processed until your user control is in VisualTree, so at the point you call "Measure", the desired size is still 0.

When I need to get the size of the FrameworkElement, I set its opacity to 0, add it to the visual tree and wait for the SizeChanged event.

+1
source

See https://msdn.microsoft.com/en-us/library/6xe5hazb(v=vs.110).aspx The byval e as PaintEventArgs parameter is not required in the example. To get only the size needed to display the entire line, you can create your own paintEventArgs field in the MeasureStringMin routine.

0
source

Source: https://habr.com/ru/post/904650/


All Articles