简体   繁体   English

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

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

I have an XML text in the WPF textbox.我在 WPF 文本框中有一个 XML 文本。

So for example, if the cursor is posited like this,例如,如果 cursor 是这样定位的,

在此处输入图像描述

or like this或者像这样

在此处输入图像描述

I want to get tag1 .我想得到tag1 And if the cursor is located in tag2 :如果 cursor 位于tag2中:

在此处输入图像描述 I get tag2 , and so on...我得到tag2 ,依此类推......

在此处输入图像描述

First, you need to define AcceptsReturn="True" in XAML, but I think you know that.首先,您需要在 XAML 中定义AcceptsReturn="True" ,但我想您知道这一点。

Then, you can use GetLineText method of TextBox in such way (I created dummy text box and event handler for purpose of presentation):然后,您可以通过这种方式使用TextBoxGetLineText方法(我创建了虚拟文本框和事件处理程序以进行演示):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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