C# WinRT-如何从文本框中获取光标处的行和列?

C# WinRT-如何从文本框中获取光标处的行和列?,c#,textbox,windows-8,microsoft-metro,windows-runtime,C#,Textbox,Windows 8,Microsoft Metro,Windows Runtime,如何从Windows 8 Metro应用程序中的文本框中获取光标处的行和列?没有像WinForms中那样的GetFirstCharIndexFromLine方法 这里有一种方法可以实现这一点: // Returns a one-based line number and column of the selection start private static Tuple<int, int> GetPosition(TextBox text) { // Selection st

如何从Windows 8 Metro应用程序中的文本框中获取光标处的行和列?没有像WinForms中那样的GetFirstCharIndexFromLine方法

这里有一种方法可以实现这一点:

// Returns a one-based line number and column of the selection start
private static Tuple<int, int> GetPosition(TextBox text)
{
    // Selection start always reports the position as though newlines are one character
    string contents = text.Text.Replace(Environment.NewLine, "\n");

    int i, pos = 0, line = 1;
    // Loop through all the lines up to the selection start
    while ((i = contents.IndexOf('\n', pos, text.SelectionStart - pos)) != -1)
    {
        pos = i + 1;
        line++;
    }

    // Column is the remaining characters
    int column = text.SelectionStart - pos + 1;

    return Tuple.Create(line, column);
}
//返回一个基于一的行号和选择开始的列
私有静态元组GetPosition(文本框文本)
{
//选择开始总是报告位置,就像换行符是一个字符一样
字符串内容=text.text.Replace(Environment.NewLine,“\n”);
int i,pos=0,line=1;
//循环浏览所有行,直到选择开始
而((i=contents.IndexOf('\n',pos,text.SelectionStart-pos))!=-1)
{
pos=i+1;
line++;
}
//列是剩余的字符
int column=text.SelectionStart-pos+1;
返回元组。创建(行、列);
}

这将获得行号和列号。

很好,但它不考虑换行,并执行不必要的替换(字符串复制)。注意,您可以使用GetRectFromCharacterIndex遍历字符,并查看它们在屏幕上的最终位置。