Wpf 更改文本时,文本框滚动到行不起作用

Wpf 更改文本时,文本框滚动到行不起作用,wpf,scroll,textbox,Wpf,Scroll,Textbox,所以我有一个文本框,当用户滚动经过某个点时,它会在文本框中加载新文本,然后它应该滚动到我告诉它滚动到的行。代码如下: public MainWindow() { InitializeComponent(); } private string fileName; private void Button_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd

所以我有一个文本框,当用户滚动经过某个点时,它会在文本框中加载新文本,然后它应该滚动到我告诉它滚动到的行。代码如下:

 public MainWindow()
    {
        InitializeComponent();
    }

    private string fileName;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();

        if (ofd.ShowDialog() == true)
        {
            TextBox1.Text = "";

            fileName = ofd.FileName;
            TextBox1.Text = System.IO.File.ReadAllText(ofd.FileName);
        }
    }

    private bool ignoreScroll = false;

    private int lineScroll = 0;

    private bool scrollToLine = false;

    int firstChange = 500;
    int i = 0;
    private void TextBox1_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {

        if (ignoreScroll)
        {
            ignoreScroll = false;
            return;
        }


            if (TextBox1.GetFirstVisibleLineIndex() > firstChange)
            {

                        ignoreScroll = true;
                      //  TextBox1.Text = "";
                        TextBox1.Text = System.IO.File.ReadAllText(fileName) ;
                        TextBox1.ScrollToLine(firstChange);
                        firstChange += 500;
                        TextBox1.Focus();
                        i++;
            }



    }
XAML:

现在,每次我加载文本时,文本实际上都会发生变化,滚动到行函数调用不会执行,文本框保持在文档顶部

为什么更改文本会使滚动到行的调用不起作用?有没有办法让这一切顺利进行

<Window x:Class="TestLoadAndScroll.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid Background="Black">
    <TextBox Name="TextBox1" ScrollViewer.ScrollChanged="TextBox1_ScrollChanged"  HorizontalAlignment="Center" Height="213" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Center" Width="406"/>
    <Button VerticalAlignment="Bottom" HorizontalAlignment="Center" Click="Button_Click" Content="Open" Height="30" Width="100" />
</Grid>
TextBox1.Text = System.IO.File.ReadAllText(fileName) ;
TextBox1.Text = System.IO.File.ReadAllText(fileName) + i;