代码之家  ›  专栏  ›  技术社区  ›  altso

在文本框中获取插入符号位置

  •  4
  • altso  · 技术社区  · 15 年前

    如何在文本框控件的可见客户端区域中获取插入符号位置(x,y)?我需要在文本框中添加自动完成功能。

    我找到了 solution for WPF ,但不能在Silverlight中应用。

    2 回复  |  直到 9 年前
        1
  •  5
  •   altso    15 年前
    public class AutoCompleteTextBox : TextBox
    {
        public Point GetPositionFromCharacterIndex(int index)
        {
            if (TextWrapping == TextWrapping.Wrap) throw new NotSupportedException();
    
            var text = Text.Substring(0, index);
    
            int lastNewLineIndex = text.LastIndexOf('\r');
    
            var leftText = lastNewLineIndex != -1 ? text.Substring(lastNewLineIndex + 1) : text;
    
            var block = new TextBlock
                            {
                                FontFamily = FontFamily,
                                FontSize = FontSize,
                                FontStretch = FontStretch,
                                FontStyle = FontStyle,
                                FontWeight = FontWeight
                            };
    
            block.Text = text;
            double y = block.ActualHeight;
    
            block.Text = leftText;
            double x = block.ActualWidth;
    
            var scrollViewer = GetTemplateChild("ContentElement") as ScrollViewer;
    
            var point = scrollViewer != null
                            ? new Point(x - scrollViewer.HorizontalOffset, y - scrollViewer.VerticalOffset)
                            : new Point(x, y);
            point.X += BorderThickness.Left + Padding.Left;
            point.Y += BorderThickness.Top + Padding.Top;
    
            return point;
        }
    }
    
        2
  •  2
  •   Community    7 年前

    除了 altso's answer ,我想说的是你确实需要打电话 .Measure() .Arrange() 块上的方法 .ActualHeight .ActualWidth 例如,要工作,请执行以下操作(参数可能因您的用例而异):

     block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
     block.Arrange(new Rect(0, 0, block.DesiredSize.Width, block.DesiredSize.Height));
     double y = block.ActualHeight;
    

    这是 必修的 在WPF中,以及 细想过的 在Silverlight(包括SL5)中。否则,您将在 ActualHeight 在wpf和silverlight中的奇怪数字(在我的例子中,这些是周围边界框的坐标 全部的 课文)。


    作为单独的解决方案,您可以使用 FormattedText 做同样的技巧。