10

Is there a way to get the size of a UIElement that resides in memory and has not yet been rendered?

I currently have a routine that creates a Grid from a DataTable and then adds the Grid into a FixedDocument. I need to know the size of the Grid because I want to automatically switch from Portrait to Landscape if needed; or even change the FontSize of the grid.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Sonny Boy
  • 7,848
  • 18
  • 76
  • 104

2 Answers2

23

You need to force a render of the item, or wait for the item to be rendered. You can then use the ActualHeight and ActualWidth properties.

To force a render:

  MenuItem item = new MenuItem();
  item.Header = "bling";
  item.Icon = someIcon;
  //Force render
  item.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
  item.Arrange(new Rect(item.DesiredSize));

In this example the MenuItem has not been given an explicit height or width. However, forcing the render will render it taking the supplied header text and icon into consideration.

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
  • `MenuItem` did not work for me, but `StackPanel` or `Viewbox` did. – vossad01 May 09 '13 at 13:22
  • There is no property called 'ActualWidth' on the class 'UIElement' :-( – Boris Sep 17 '13 at 05:46
  • Occasionally complex controls may not be correctly rendered if you have a lot of panels being hidden - this is what I had to do to work around it : http://stackoverflow.com/questions/41966704/wpf-xaml-control-converted-to-an-image-has-incorrect-layout/41966743#41966743 – Simon_Weaver Jan 31 '17 at 20:21
1

You can only determine this if there is an explicit Width or Height set. Even then, depending on the scenario, it may change at render time, since the Layout pass will not occur until it's rendered, and ActualWidth/ActualHeight get set.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • So my only option is to repeatedly render the control using differing font sizes and page layouts until it fits? – Sonny Boy Feb 03 '11 at 18:29
  • @Sonny: That, or render it to some other location... You could always use RenderTargetBitmap, etc, to try to render it "off screen" and then adjust, if you don't want to have the user see it... – Reed Copsey Feb 03 '11 at 18:32