因为UWP目前的TextBox没有ScrollToCaret();方法
因此自己写了一个,冻皮西凑吧,跳转到选中文本的方法.
UWP TextBox Scroll to Selected text
private async void ScrollToSelected(TextBox textBox)
{
var grid = (Grid)VisualTreeHelper.GetChild(textBox, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer)) continue;
//
int start = textBox.SelectionStart;
double line_height = 0;
int line_number = 0;
var content = textBox.Text;
//
await Task.Run(() => {
try
{
//声明匹配规则对象,并设定匹配规则
Regex regex = new Regex("\r");//构造方法里面的参数就是匹配规则。
MatchCollection matchs;
matchs = regex.Matches(content);
line_number = matchs.Count + 1;
if (line_number==0)
{
line_number = 1;
}
}
catch (Exception ex)
{
return;
}
});
var scroll_height = ((ScrollViewer)obj).ExtentHeight;
line_height = scroll_height / line_number;
Debug.WriteLine($"line_number:{line_number}lineheight:{line_height}");
double selectHeight=0;
double line_number2;
await Task.Run(() => {
try
{
Regex regex = new Regex("\r");
MatchCollection matchs;
matchs = regex.Matches(content.Substring(0, start));
line_number2 = matchs.Count;
selectHeight = line_number2 * line_height;
Debug.WriteLine($"line_number2:{line_number2}selectHeight:{selectHeight}");
}
catch (Exception ex)
{
return;
}
});
((ScrollViewer)obj).ChangeView(0.0f, selectHeight, 1.0f, true);
break;
}
}
end