Let's say I have TextBlock
with text "Some Text" and font size 10.0.
How I can calculate appropriate TextBlock
width?
Use the FormattedText
class.
I made a helper function in my code:
private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
candidate,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
this.textBlock.FontSize,
Brushes.Black,
new NumberSubstitution(),
1);
return new Size(formattedText.Width, formattedText.Height);
}
It returns device-independent pixels that can be used in WPF layout.