views:

256

answers:

2

Hello, I have this problem. I need to know the size a Label is trying to use, but since the control that contains it is smaller than the actual label, when I call label.ActualWidth, what I really get is the width of said container control. Is there a way to get the width that the label would require to fit its content (disregarding its ACTUAL width)? Something like label.RequiredWidth, neither label.DesiredSize.Width or label.ActualWidth work.

Here's what I'm trying:

XAML:

<StackPanel Width="100">
    <Label x:Name="aLabel">Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text </Label>
</StackPanel>

C#:

aLabel.ActualWidth; // this is 100 like the StackPanel
aLabel.DesiredSize.Width; // also 100 like the StackPanel

Thank you.

+1  A: 

One way to do this would be to measure the length of the text, using Glyph widths. The following method accomplishes that:

public static double GetGlyphRunWidth(Typeface typeface, string text, int fontSize)
 {
  GlyphTypeface glyphTypeface;
  if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
   return 0;

  ushort[] glyphIndexes = new ushort[text.Length];
  double[] advanceWidths = new double[text.Length];

  double totalWidth = 0;
  for (int n = 0; n < text.Length; n++)
  {
   ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];
   totalWidth += glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
  }

  return totalWidth;
 }
Charlie
The size I get using this is extremely accurate to the real size of the label (adding label.Padding.Left and Right of course) Thanks!!
Carlo
+1  A: 

Here's the answer:

lb1.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var requiredSize = lb1.DesiredSize;

Note, that this won't do any automatic text wrapping for you.

Oleg Mihailik
This is a lot simpler. Thanks.
Carlo