WPF textBox 字符串搜索,滚动到当前行

Posted want_Success

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF textBox 字符串搜索,滚动到当前行相关的知识,希望对你有一定的参考价值。

 1 //执行事件 
 2 private void Button_Click(object sender, RoutedEventArgs e)
 3         {
 4 
 5             if (txtstr.Text == "")
 6             {
 7                 MessageBox.Show("查询字符串为空!");
 8                 return;
 9             }
10             CXtxt_string();
11         }
12 
13 //执行方法
14         int index = 0;//从第0个字符串开始查找
15         public void CXtxt_string()
16         {
17             string str = textBox1.Text;//设置需要查找的字符串
18             index = textBox2.Text.IndexOf(str , index);//返回str在textBox1中的索引位置
19             if (index < 0)//如果没有找不到字符串,则return
20             {
21                 index = 0;
22                 textBox2.SelectionStart = 0;
23                 textBox2.SelectionLength = 0;
24                 MessageBox.Show("已到结尾");
25                 return;
26             }
27             textBox2.SelectionStart = index;//设置需要选中字符串的开始位置
28             textBox2.SelectionLength = str.Length;//设置需要选中字符串的结束位置
29             index++;
30             textBox2.Focus();//设置焦点
31 
32             //int rows = textBox2.GetFirstVisibleLineIndex();//得到可见文本框中第一个字符的行索引
33             int line = textBox2.GetLineIndexFromCharacterIndex(index);//返回指定字符串索引所在的行号
34             //Debug.WriteLine(rows + ",," + line);
35             int lastline = textBox2.GetLastVisibleLineIndex();
36             if (line > lastline)
37             {
38                 textBox2.ScrollToLine(lastline+1);//滚动到视图中指定行索引
39             }
40         }
41     }
42 }

WPF 在textBox查找字符串并且自动滚动到字符串所在的行

以上是关于WPF textBox 字符串搜索,滚动到当前行的主要内容,如果未能解决你的问题,请参考以下文章

WPF编程:textbox控件文本框数据显示最后一行

WPF 后台实现按数字键滚动DataGrid 当前选中项

WPF 后台实现按数字键滚动DataGrid 当前选中项

使用 MVVM 从 WPF 中的 TextBox 进行正确的 DataGrid 搜索

WPF关于Tooltip的Binding

使用 TextBox 和 DatePicker 元素过滤 WPF DataGrid 行