如何使wpf文本块自动调整大小

时间:2010-09-24 04:54:18

标签: c# wpf

我有一个文本块,我动态添加字符串.. 即使我添加字符串宽度并更新文本块,文本块也没有显示适当的宽度,仍然会剪切一些文本..

如何测量必须在文本块中显示的宽度? 以及如何使其自动调整大小?

5 个答案:

答案 0 :(得分:6)

您可以使用以下解决方案获取文字大小:

解决方案1 ​​

您可以使用FormattedText来测量文本的大小,这是一个示例:

String text = "Here is my text";
Typeface myTypeface = new Typeface("Helvetica");
FormattedText ft = new FormattedText(text, CultureInfo.CurrentCulture, 
        FlowDirection.LeftToRight, myTypeface, 16, Brushes.Red);

Size textSize = new Size(ft.Width, ft.Height);

解决方案2

使用Graphics类(找到here):

System.Drawing.Font font = new System.Drawing.Font("Calibri", 12, FontStyle.Bold);
Bitmap bitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bitmap);
SizeF measureString = g.MeasureString(text, font);

你在这里!

答案 1 :(得分:3)

没有指定高度或宽度的文本块会自动扩展,直到它们为止 填满他们的容器。所以试试吧。

答案 2 :(得分:3)

这是我编写的一个课程。它只是AutoShrinks,但您可以添加所需的功能。如果已设置,则使用父边界OR MaxHeight / MaxWidth。

public class TextBlockAutoShrink : TextBlock
{
    // private Viewbox _viewBox;
    private double _defaultMargin = 6;
    private Typeface _typeface;

    static TextBlockAutoShrink()
    {
        TextBlock.TextProperty.OverrideMetadata(typeof(TextBlockAutoShrink), new FrameworkPropertyMetadata(new PropertyChangedCallback(TextPropertyChanged)));
    }

    public TextBlockAutoShrink() : base() 
    {
        _typeface = new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch, this.FontFamily);
        base.DataContextChanged += new DependencyPropertyChangedEventHandler(TextBlockAutoShrink_DataContextChanged);
    }

    private static void TextPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        var t = sender as TextBlockAutoShrink;
        if (t != null)
        {
            t.FitSize();
        }
    }

    void TextBlockAutoShrink_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        FitSize();
    }

    protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
    {
        FitSize();

        base.OnRenderSizeChanged(sizeInfo);
    }

    private void FitSize()
    {
        FrameworkElement parent = this.Parent as FrameworkElement;
        if (parent != null)
        {
            var targetWidthSize = this.FontSize;
            var targetHeightSize = this.FontSize;

            var maxWidth = double.IsInfinity(this.MaxWidth) ? parent.ActualWidth : this.MaxWidth;
            var maxHeight = double.IsInfinity(this.MaxHeight) ? parent.ActualHeight : this.MaxHeight;

            if (this.ActualWidth > maxWidth)
            {
                targetWidthSize = (double)(this.FontSize * (maxWidth / (this.ActualWidth + _defaultMargin)));
            }

            if (this.ActualHeight > maxHeight)
            {
                var ratio = maxHeight / (this.ActualHeight);

                // Normalize due to Height miscalculation. We do it step by step repeatedly until the requested height is reached. Once the fontsize is changed, this event is re-raised
                // And the ActualHeight is lowered a bit more until it doesnt enter the enclosing If block.
                ratio = (1 - ratio > 0.04) ? Math.Sqrt(ratio) : ratio;

                targetHeightSize = (double)(this.FontSize *  ratio);
            }

            this.FontSize = Math.Min(targetWidthSize, targetHeightSize);
        }
    }
}

答案 3 :(得分:1)

以下是解决此问题的另一种方法。

设置yourTextBlock.Width = double.NaN,与Height相同。

答案 4 :(得分:1)

默认情况下,元素的HorizontalAligmentVerticalAligment属性设置为Stretch,因此它们将适应其父级。

但是,如果将它们设置为Center,则该元素将保持其自然大小,因此您可以对此进行测试(或使用代码而非XAML设置属性):

<TextBlock Text="This is my text"
      HorizontalAlignment="Center"
      VerticalAlignment="Center"
/>

在我的情况下可能奏效,也许并非在每种情况下都行。