简体   繁体   中英

WPF TextBox ScrollToLine not updating if visible

I have a Navigation-bar in my program that allows you to navigate the different sections in my TextBox, but the problem I have is that this doesn't work if the Text I am scrolling to is already visible on the screen.

Like in this example, if I try to jump from Section 1 to Section 3, it won't work as it's already visible.

示例 1

But, in this example if I jump to Section 3, it works fine as it's not already visible.

示例 2

The scrolling function I use is very simple:

if (nLine > 0 && nLine <= textBox.LineCount)
    textBox.ScrollToLine(nLine - 1); 

I hope that someone can shed some light on an alternative solution that allows me to scroll even if the text is already visible.

Edit: Added solution.

This is a code snippet from my project.

private static void ScrollToLineCallback(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
    var textBox = (TextBox)target;

    int newLineValue;
    if (Int32.TryParse(e.NewValue.ToString(), out newLineValue))
    {
        if (newLineValue > 0 && newLineValue <= textBox.LineCount) // Validate
        {
            textBox.ScrollToLine(newLineValue - 1); // Scroll to Line

            // Check and see if we are at the line we want.
            if (textBox.GetFirstVisibleLineIndex() <= newLineValue && textBox.GetLastVisibleLineIndex() >= newLineValue)
            {
                // If not lets move to the desired location
                int newLineCorrectionValue = newLineValue - textBox.GetFirstVisibleLineIndex() - 2; // How much further do we need to scroll down?

                for (int i = 0; i < newLineCorrectionValue; i++)
                {
                    textBox.LineDown(); // Scroll down
                }
            }
        }
    }
}

You could use GetCharacterIndexFromLineIndex to get the index of the beginning of the desired line and then set the CaretIndex to that value.

Because I don't really know, what you are trying to achieve, another possibility is to use LineUp and LineDown in conjunction with GetFirstVisibleLineIndex and GetLastVisibleLineIndex .

private void TextBoxGotoLine(
    TextBox textbox1, 
    int linenum)
{
  var target_cpos = textbox1.GetCharacterIndexFromLineIndex(linenum);
  var target_char_rect = textbox1.GetRectFromCharacterIndex(target_cpos);
  var first_char_rect = textbox1.GetRectFromCharacterIndex(0);
  textbox1.ScrollToVerticalOffset(
   target_char_rect.Top - 
   first_char_rect.Top
 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM