如何在没有 NoWrap 的 TextBox 中跟踪文本的结尾?

Ira*_* JW 5 .net c# wpf textbox

我有一个文本框xaml

<TextBox Name="Text" HorizontalAlignment="Left" Height="75"   VerticalContentAlignment="Center" TextWrapping="NoWrap" Text="TextBox" Width="336"  BorderBrush="Black" FontSize="40" />
Run Code Online (Sandbox Code Playgroud)

我使用此方法向其添加文本:

private string words = "Initial text contents of the TextBox.";

public async void textRotation()
{
    for(int a =0; a < words.Length; a++)
    {
        Text.Text = words.Substring(0,a);
        await Task.Delay(500);
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦文本脱离包装,有一种方法可以将结尾集​​中起来,这样旧文本就会消失在左侧,而新文本会在右侧消失,而不是直接将其添加到右侧而看不到。

Jim*_*imi 6

一个快速的方法是wordsTextRenderer.MeasureText测量需要滚动的字符串 ( ) ,将width测量度量等于字符串中字符数的部分,然后使用ScrollToHorizo​​ntalOffset()执行滚动:

public async void textRotation()
{
    float textPart = TextRenderer.MeasureText(words, new Font(Text.FontFamily.Source, (float)Text.FontSize)).Width / words.Length;
    for (int i = 0; i < words.Length; i++)
    {
        Text.Text = words.Substring(0, i);
        await Task.Delay(100);
        Text.ScrollToHorizontalOffset(textPart * i);
    }
}
Run Code Online (Sandbox Code Playgroud)

相同,但使用FormattedText类来测量字符串:

public async void textRotation()
{
    var textFormat = new FormattedText(
        words, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
        new Typeface(this.Text.FontFamily, this.Text.FontStyle, this.Text.FontWeight, this.Text.FontStretch),
        this.Text.FontSize, null, null, 1);

    float textPart = (float)textFormat.Width / words.Length;
    for (int i = 0; i < words.Length; i++)
    {
        Text.Text = words.Substring(0, i);
        await Task.Delay(200);
        Text.ScrollToHorizontalOffset(textPart * i);
    }
}
Run Code Online (Sandbox Code Playgroud)

WPF 滚动文本