Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将选定文本的开始索引和结束索引转换为精确的TextRange?_C#_.net_Wpf - Fatal编程技术网

C# 如何将选定文本的开始索引和结束索引转换为精确的TextRange?

C# 如何将选定文本的开始索引和结束索引转换为精确的TextRange?,c#,.net,wpf,C#,.net,Wpf,我可以在RichTextBox中获得所选文本的确切开始和结束索引,但如何实现相反的操作?使用实际的开始和结束索引(字符位置)再次选择文本作为一个范围,对其执行一些格式化,如突出显示背景 示例-使用鼠标选择的文本与应用的高光不重叠 编辑: 我只能处理由highlightFromSelection()方法确定的绝对字符位置。可能重复的@Harsh请删除重复标志,这是winforms,这是wpf您尝试过这个解决方案吗?我想这里已经回答了:@Harsh我想这是我能找到的最接近的 private voi

我可以在RichTextBox中获得所选文本的确切开始和结束索引,但如何实现相反的操作?使用实际的开始和结束索引(字符位置)再次选择文本作为一个范围,对其执行一些格式化,如突出显示背景

示例-使用鼠标选择的文本与应用的高光不重叠

编辑:
我只能处理由highlightFromSelection()方法确定的绝对字符位置。

可能重复的@Harsh请删除重复标志,这是winforms,这是wpf您尝试过这个解决方案吗?我想这里已经回答了:@Harsh我想这是我能找到的最接近的
private void textBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if(this.textBox.Selection.Text.Length > 0)
        highlightFromSelection(this.textBox, new SolidColorBrush(Colors.Yellow));
}

public void highlightFromSelection(RichTextBox textBox, SolidColorBrush color)
{
    TextPointer docStart = textBox.Document.ContentStart;

    TextPointer selectionStart = textBox.Selection.Start;
    TextPointer selectionEnd = textBox.Selection.End;

    TextRange start = new TextRange(docStart, selectionStart);
    TextRange end = new TextRange(docStart, selectionEnd);

    int indexStart = start.Text.Length;
    int indexEnd = end.Text.Length;

    MessageBox.Show("start: " + indexStart + " end: " + indexEnd);

    ApplyHighlight(textBox, indexStart, indexEnd, color);
}

public void ApplyHighlight(RichTextBox textBox, int startIndex, int endIndex, SolidColorBrush color)
{
    TextPointer docStart = textBox.Document.ContentStart;

    //This code highlights the wrong part of text - its the closest I could get 
    //i.e. the highlighting does not overlap exactly with the original selection made

    //TextPointer startPointer = docStart.GetPositionAtOffset(startIndex, LogicalDirection.Forward);
    //TextPointer endPointer = docStart.GetPositionAtOffset(endIndex, LogicalDirection.Backward);
    //TextRange range = new TextRange(startPointer, endPointer);
    //range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
}