Calculating Label Size in Codebehind

Nathan Sokalski 4,116 Reputation points

I need to determine the size of multiple Label(s) in codebehind. My reason for doing this is to determine which one is widest/tallest. Waiting until they are rendered & visible would be very inefficient because that would mean displaying & resizing all the Label(s) multiple times. What I would like to do is use an "imaginary" Label (one that is declared in codebehind but never actually added to the UI). However, this does not seem to work because the measuring does not happen if the Label is not displayed (which could also cause a problem if they are scrolled out of view in the initial layout). Is there a way to determine the size that a Label will require before it is actually rendered (sort of a virtual rendering)? Thanks.

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,287 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Alessandro Caliaro 4,181 Reputation points

    I think you can use

        Label label = new Label();
        label.SizeChanged += Label_SizeChanged;

    SizeChanged fires when the size change so you can get height and width

  2. Nathan Sokalski 4,116 Reputation points

    Will that work for Label(s) that are never displayed? I know it sounds strange to need the size of something that will never be displayed, but I need to know it so that everything is aligned if the user does scroll to those elements. If I wait until they are rendered, layout passes, resizing, and scrolling will repeating exponentially. The Label(s) are in the ItemTemplate(s) of CollectionView(s), so resetting the ItemsSource would be a major performance hit. When the rendering engine does the layout, how does that get the size? Having access to that code would be great (although it's probably not available to us). Is there a way to simulate the measuring without causing a performance hit?