所以我有一个文本框,当用户滚动通过某个点时,它会在文本框中加载新文本,然后它应滚动到我告诉它滚动到的行。这是代码:
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;
现在文本实际上每次加载时都会更改,并且滚动到行函数调用不会被执行,文本框会保留在文档的顶部。
为什么更改文本会使调用滚动到行不起作用?有没有办法使这项工作?