Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining size of a control before rendering process

Tags:

wpf

controls

size

I've got a composite control consisting of a rectangle and a few dynamically created labels (dynamically, because during design time I don't know how many labels shall be displayed). The labels' positions (margins) are evaluated during run time by combining whole control size, additional collection passed through dependency property and by heights of labels themselves.

Unfortunately, I didn't came into deterministic way of determining label height before one was rendered. ActualWidth and ActualHeight are 0 before the labels are displayed, Width/Height is not set, because I wish the labels to size themselves basing on their contents, DesiredSize returns either 0, correct size or size exceeding the real label size (like 2 or 3 times), RenderSize returns either valid size or 0 and it is like first label returns valid size and second one - 0.0, without any noticeable reason.

I've tried calling Measure() on the labels with double.PositiveInfinity passed by only to reach situation, when DesiredSize was way bigger than expected (all labels have the same font and consist only of numbers, so they all shall have more less similar size, but first had ~16 pixels, second - ~36, though after the rendering, RenderSize was valid for both of them).

Is there a deterministic way to check desired control size, based only on its contents (not on alignment/margins) before it is rendered on screen?

like image 395
Spook Avatar asked May 17 '11 10:05

Spook


1 Answers

You can use UpdateLayout to force a measure / layout pass. After invoking this method ActualWidth and ActualHeight will have the correct values.

like image 178
ColinE Avatar answered Sep 17 '22 23:09

ColinE