WPF TextBlock:如何均匀分隔显示的字符?

Ser*_*ier 4 wpf textblock

我需要显示一个字符串,每个x像素显示一个字符.(x是整个字符串).

例如:"你好" - >位置(像素)0处的H,位置50处的e,100处的l,150处的1,以及200处的o.

当然我可以为每个角色使用TextBlock,但它似乎有点过分.

TranslateTransform似乎没有做到这一点:它相对于前一个角色的END偏移我的角色,这不是我想要的.

TIA的帮助.

Ken*_*art 6

我不相信在WPF中这样做有内在的能力,但我可能是错的.

下面的代码演示了如何编写自己的控件来为您执行此操作.它效率不高,它可以通过调整来实现,包括控制字体等的更多属性,但你明白了:

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Window1.xaml:

<local:SpacedTextBlock Text="Hello"/>
Run Code Online (Sandbox Code Playgroud)

结果:

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