简体   繁体   中英

How do I get xml tag from cursor position in c# wpf textbox

I have an XML text in the WPF textbox.

So for example, if the cursor is posited like this,

在此处输入图像描述

or like this

在此处输入图像描述

I want to get tag1 . And if the cursor is located in tag2 :

在此处输入图像描述 I get tag2 , and so on...

在此处输入图像描述

First, you need to define AcceptsReturn="True" in XAML, but I think you know that.

Then, you can use GetLineText method of TextBox in such way (I created dummy text box and event handler for purpose of presentation):

private void txb_KeyDown(object sender, KeyEventArgs e)
{
    // Handle event only if Q is pressed.
    if (e.Key != Key.Q) return;
    // Count how many newline characters there were, to determine index of current line.
    var lineIndex = txb.Text.Substring(0, txb.CaretIndex).Count(ch => ch == '\n');
    // Get current line.
    var currentLine = txb.GetLineText(lineIndex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM