我有一个带有大量文本的.NET UWP TextBox,我想在其中搜索一个单词。当我点击按钮开始搜索时,它会找到该单词的第一个出现位置。当我再次点击时,它会找到第二个,如记事本中的ctrl + f)。
我希望专注于已发现的世界,但是当文本足够长以至于有滚动条时,它不会将找到的单词放入视图中。
这是此屏幕的屏幕截图,显示我必须调整窗口大小以查看找到的单词。
以下是我的搜索代码(textarea.Focus(FocusState.Programmatic);
类型为TextBox):
textarea.Focus(FocusState.Pointer);
我已经尝试将SelectionStart
放在方法的末尾以及SelectionStart
,但都没有帮助。
更新
我发现它正确聚焦,但是找到最后找到的单词(到位置,找到下一个单词之前的光标位置),而不是找到当前找到的单词。
所以我需要将焦点更新为当前{{1}},而不是最后一个。有任何想法吗?我已经尝试再次更改{{1}},替换文本和更新布局 - 没有任何帮助。
答案 0 :(得分:1)
您可以做的是测量文本的高度直到索引,并相应地调整文本框的大小。
private static float GetTextHeightUntilIndex(TextBox textBox, int index)
{
var height = 0;
var textBuffer = textBox.Text;
// Remove everything after `index` in order to measure its size
textBox.Text = textBuffer.Substring(0, index);
textBox.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
var height = textBox.DesiredSize().Height;
// Put the full text back
textBox.Text = textBuffer;
return height;
}
private void Find(string text)
{
textarea.Focus(FocusState.Programmatic);
var start = textarea.SelectionStart + textarea.SelectionLength;
var found = (bool)checkboxFindCaseSensitive.IsChecked ? textarea.Text.IndexOf(text, start) : textarea.Text.IndexOf(text, start, StringComparison.CurrentCultureIgnoreCase);
if (found == -1)
{
textarea.SelectionStart = 0;
found = (bool)checkboxFindCaseSensitive.IsChecked ? textarea.Text.IndexOf(text, start) : textarea.Text.IndexOf(text, start, StringComparison.CurrentCultureIgnoreCase);
if (found == -1) return;
}
textarea.SelectionStart = found;
textarea.SelectionLength = text.Length;
// -------------------
var cursorPosInPx = GetTextHeightUntilIndex(textarea, found);
// First method: resize your textbox to the selected word
textarea.Height = cursorPosInPx;
// Second method: scroll the textbox
var grid = (Grid)VisualTreeHelper.GetChild(textarea, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (obj is ScrollViewer)
((ScrollViewer)obj).ChangeView(null, cursorPosInPx, null, true);
}
}
但要注意,对于第一种方法,根据文本框的布局,调整控件的大小可能会产生不良影响或根本没有影响。