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

前端 未结 2 776
滥情空心
滥情空心 2020-12-03 23:36

I have a TextBox in xaml:



        
2条回答
  •  不知归路
    2020-12-04 00:03

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

提交回复
热议问题