Measuring controls created at runtime in WPF

前端 未结 3 479
悲&欢浪女
悲&欢浪女 2021-02-04 05:29

I recognise this is a popular question but I couldn\'t find anything that answered it exactly, but I apologise if I\'ve missed something in my searches.

I\'m trying to c

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 05:38

    The control won't have a size until WPF does a layout pass. I think that happens asynchronously. If you're doing this in your constructor, you can hook the Loaded event -- the layout will have happened by then, and any controls you added in the constructor will have been sized.

    However, another way is to ask the control to calculate what size it wants to be. To do that, you call Measure, and pass it a suggested size. In this case, you want to pass an infinite size (meaning the control can be as large as it likes), since that's what Canvas is going to do in the layout pass:

    lb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
    Debug.WriteLine(lb.DesiredSize.Width);
    

    The call to Measure doesn't actually change the control's Width, RenderSize, or ActualWidth. It just tells the Label to calculate what size it wants to be, and put that value in its DesiredSize (a property whose sole purpose is to hold the result of the last Measure call).

提交回复
热议问题