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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With