查找多个TextBlock的最大可能字体大小

时间:2012-09-18 10:09:19

标签: c# wpf windows-8 microsoft-metro

我在固定尺寸列TextBlock中有几个Grid个。即Grid大小可能会更改,但其列宽相同(例如整个大小的10%),每列包含TextBlock

所有TextBlock s 必须的字体大小相同。

如何找到最大可能的字体大小,使TextBlock内的所有文字都可见?

1 个答案:

答案 0 :(得分:0)

您可以使用Graphics.MeasureString Method (String, Font, Int32)来计算字体大小。 然后使用一些行为魔法将字体大小绑定到TextBlock。

private void MeasureStringWidth(PaintEventArgs e)
{

    // Set up string. 
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Set maximum width of string. 
    int stringWidth = 200;

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
相关问题