我有一个TextBox。我希望用户能够在其中单击;当他这样做时,红色标记线应出现在最靠近咔哒位置的两个字符之间,并保留在此处。用户可以多次这样做。
我是WPF的新手,但我想,就像在Winforms中一样,我将不得不破解凌乱的OnRender方法。到目前为止,没关系。
我真正想知道的是:如何将两个最接近的字符放到点击位置?
我正要进行像素检查,但看起来很重。
答案 0 :(得分:-1)
您可以尝试:
textBox.GetCharacterIndexFromPoint(point, true);
答案 1 :(得分:-2)
我发现了我想做的事情,而且比我想象的要简单得多(尽管找到实际的方式很痛苦)。
只需将此处理程序添加到文本框的SelectionChanged事件:
private void placeMarker(object sender, RoutedEventArgs e)
{
// txt_mark is your TextBox
int index = txt_mark.CaretIndex;
// I don't want the user to be able to place a marker at index = 0 or after the last character
if (txt_mark.Text.Length > first && first > 0)
{
Rect rect = txt_mark.GetRectFromCharacterIndex(first);
Line line = new Line();
// If by any chance, your textbox is in a scroll view,
// use the scroll view's margin instead
line.X1 = line.X2 = rect.Location.X + txt_mark.Margin.Left;
line.Y1 = rect.Location.Y + txt_mark.Margin.Top;
line.Y2 = rect.Bottom + txt_mark.Margin.Top;
line.HorizontalAlignment = HorizontalAlignment.Left;
line.VerticalAlignment = VerticalAlignment.Top;
line.StrokeThickness = 1;
line.Stroke = Brushes.Red;
// grid1 or any panel you have
grid1.Children.Add(line);
// set the grid position of the line to txt_mark's (or the scrollview's if there is one)
Grid.SetRow(line, Grid.GetRow(txt_mark));
Grid.SetColumn(line, Grid.GetColumn(txt_mark));
}
}
您可能需要添加一些字距调整,或者只是增加标记的字体大小,以免破坏可读性。