Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

wpf

textbox

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.

like image 839
Ira Watt Avatar asked Dec 31 '18 16:12

Ira Watt


2 Answers

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(Text.FontFamily, Text.FontStyle, Text.FontWeight, Text.FontStretch),
        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

like image 155
Jimi Avatar answered Nov 14 '22 22:11

Jimi


It should be fairly easy to achieve, try to add this code:

public async void textRotation()
    {
        for(int a =0; a < words.Length; a++)
        {
            Text.Text = words.Substring(0,a);
            Text.ScrollToHorizontalOffset(Text.Text.Last());
            await Task.Delay(500);

        }
    }
like image 36
Dark Templar Avatar answered Nov 14 '22 22:11

Dark Templar