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

Silverlight 获取文本框中的插入符号位置,silverlight,Silverlight,如何在TextBox控件的可见客户端区域中获取插入符号位置(x,y)?我需要在文本框中添加自动完成功能 我已经找到了,但是它不能在Silverlight中应用。此外,我想提到的是,您实际上需要调用块上的.Measure()和.Arrange()方法,以便.ActualHeight和.ActualWidth工作,例如,这样(参数可能根据您的用例而有所不同): public class AutoCompleteTextBox : TextBox { public Point GetPosit

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

我已经找到了,但是它不能在Silverlight中应用。

此外,我想提到的是,您实际上需要调用块上的
.Measure()
.Arrange()
方法,以便
.ActualHeight
.ActualWidth
工作,例如,这样(参数可能根据您的用例而有所不同):

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;
    }
}
这在WPF中是必需的,在Silverlight(包括SL5)中是建议的。否则,WPF中的实际高度将为0,而Silverlight中的数字则会很奇怪(在我的例子中,这些是所有文本周围边界框的坐标)


作为一个单独的解决方案,您可以使用类执行相同的操作

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