2

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

4

1 回答 1

2

这是实现此目的的一种方法:

// 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);
}

这将获得行号和列号。

于 2012-10-02T01:50:19.097 回答