Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - How to follow the end of a text in a TextBox with no NoWrap?

I have a TextBox in xaml:

<TextBox Name="Text" HorizontalAlignment="Left" Height="75"   VerticalContentAlignment="Center" TextWrapping="NoWrap" Text="TextBox" Width="336"  BorderBrush="Black" FontSize="40" />

I add text to it with this method:

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

Once the text goes of out of the wrap is there a way to focus the end so the old text disappears to the left and the new on the right, as opposed to just adding it to the right without seeing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A quick method is to measure the string (words) that needs scrolling with TextRenderer.MeasureText, divide the width measure in parts equals to the number of chars in the string and use ScrollToHorizontalOffset() to perform the scroll:

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

Same, but using the FormattedText class to measure the string:

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

WPF scrolling text


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...