如何使wpf文本块自动大小化?

问题描述 投票:4回答:5

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

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

c# wpf
5个回答
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类(可以在 此处 ):

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);

Here you are !


3
投票

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


3
投票

这是我写的一个类,可以做到这一点。它只是自动收缩,但你可以添加你需要的功能。它使用父界或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);
        }
    }
}

1
投票

下面是解决这个问题的另一种方法。

设置 yourTextBlock.Width = double.NaN 同理 Height.


1
投票

默认情况下,元素有一个 HorizontalAligmentVerticalAligment 属性,设置为 Stretch,所以他们会适应他们的父母。

但如果你把这些设置为 Center元素将保持其自然大小,所以你可以测试一下(或使用代码而不是XAML设置属性)。

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

在我的情况下,它的工作,也许不是在所有情况下。

© www.soinside.com 2019 - 2024. All rights reserved.