WPF TextBlock: How to evenly space displayed characters?

偶尔善良 提交于 2019-12-01 07:33:25
Kent Boogaart

I don't believe there's an in-built abilty to do this in WPF, but I could be wrong.

The code below demonstrates how you could write your own control to do this for you. It isn't efficient, and it could do with tweaking, including more properties to control font etcetera, but you get the idea:

SpacedTextBlock.cs:

public class SpacedTextBlock : Control
{
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
        typeof(string),
        typeof(SpacedTextBlock));

    public string Text
    {
        get { return GetValue(TextProperty) as string; }
        set { SetValue(TextProperty, value); }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        if (Text != null)
        {
            var widthPerChar = ActualWidth / Text.Length;
            var currentPosition = 0d;

            foreach (var ch in Text)
            {
                drawingContext.DrawText(new FormattedText(ch.ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), 12, Foreground), new Point(currentPosition, 0));
                currentPosition += widthPerChar;
            }
        }
    }
}

Window1.xaml:

<local:SpacedTextBlock Text="Hello"/>

Result:

alt text http://img199.imageshack.us/img199/8022/screenshotud.png

I guess it depends on the details of your situation whether this will work or not. But could you just add spaces between each letter, and set the text alignment to be justified?

Unfortunately you don't get to set the # of pixels this way if that's what you need... but you can get even spacing this way. If this isn't just one spot on your window or is a little more complex with dynamic text... then you may want to look into a more elegant solution.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!