TextBox定位到指定文字处

发布时间 2023-07-22 11:32:00作者: 户的博客

新建时是 WPF应用程序 的程序,框架 .NET 6

xaml中

<TextBox x:Name="txt" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True"></TextBox>
AcceptsReturn="True" 输入enter时可以换行,之前是不换行的

cs中

int index = content.IndexOf("test");
txt.ScrollToLine(txt.GetLineIndexFromCharacterIndex(index)); //GetLineIndexFromCharacterIndex 偶尔会返回下一行


搜索“TextBox将光标定位到指定文字处”,有
1)https://blog.csdn.net/qq_42528923/article/details/123912963的,int index=123;//指定任意位置 this.textBox1.SelectionStart = index; // this.textBox1.Select(this.textBox1.SelectionStart, 0); 没用
2)https://blog.csdn.net/qq_21090131/article/details/83716873的,txtBox.SelectionStart = int_num; txtBox.ScrollToCaret(); 没用
3)https://it.cha138.com/jingpin/show-3705114.html的,RichTextBox定位,没试过
4)https://cloud.tencent.com/developer/ask/sof/799535/answer/1158398的,textBox.ScrollToHorizontalOffset(double.PositiveInfinity);没用
5)https://stackoverflow.com/questions/23766634/wpf-textbox-scroll-to-end-only-works-once的,
txt.SelectionStart = index; this.txt.Select(this.txt.SelectionStart, 0); var rect = txt.GetRectFromCharacterIndex(txt.CaretIndex); txt.ScrollToVerticalOffset(rect.Top); 有时定位准有时定位到莫名其妙的地方
6)https://outofmemory.cn/tougao/10922936.html的,//滚动到光标处 this.textBox1.ScrollToCaret(); WPF框架.NET 6没找到这个方法
7)https://www.it1352.com/2810517.html的,textBox.ScrollToLine(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart)); 可行
回车不添加新行AcceptsReturn="True",https://www.it1352.com/2437270.html的