代码之家  ›  专栏  ›  技术社区  ›  MBZ

为多个文本块查找可能的最大字体大小

  •  0
  • MBZ  · 技术社区  · 12 年前

    我有几个 TextBlock s在固定大小的列中 Grid .即 网格 大小可能会改变,但其列宽都相同(例如,占整个大小的10%),并且每列包含一个 控件

    所有的字体大小 控件 s 必须 是一样的。

    我如何找到使所有文本都在里面的最大字体大小 控件 是可见的吗?

    1 回复  |  直到 12 年前
        1
  •  0
  •   Ralf de Kleine    12 年前

    你可以使用 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));
    }