将 RichTextBox.Selection.Start 转换为整数。

huangapple go评论50阅读模式
英文:

How to convert RichTextBox.Selection.Start to int?

问题

如何将RichTextBox.Selection.Start转换为int?

在WinForms中,您可以这样做:

int i = richTextBox.SelectionStart;

在WPF中如何做同样的事情?

我只需要选择的起始位置的整数值。

我尝试查找关于这个问题的信息,但一切都徒劳无功。在WPF的RichTextBox.Selection.Start中有相当多的方法,但似乎没有一个能提供所需的结果。如此简单的任务却出现了如此多困难,真是令人费解。

英文:

How to convert RichTextBox.Selection.Start to int?

In winforms, you can do this :

int i = richTextBox.SelectionStart;

How to do the same in WPF?

All I need is the int value of the start position of the selection.

I tried to find information on this issue, but all was in vain. There are quite a few methods in RichTextBox.Selection.Start in wpf, but none seem to give the desired result. It is very strange that so many difficulties arose with such a simple task.

答案1

得分: 1

获取选择部分的起始位置和文档的起始位置作为 TextPointer。然后,您可以使用 GetOffsetToPosition 方法来计算它们之间的文本符号距离。

TextPointer selStart = richTextBox.Selection.Start;
TextPointer docStart = richTextBox.Document.ContentStart;
int offset = docStart.GetOffsetToPosition(selStart);
英文:

Get both the start of the selection and the start of the document as a TextPointer. You can then use the GetOffsetToPosition method to calculate the distance between the two in text symbols.

TextPointer selStart = richTextBox.Selection.Start;
TextPointer docStart = richTextBox.Document.ContentStart;
int offset = docStart.GetOffsetToPosition(selStart);

答案2

得分: 0

以下是翻译好的内容:

"从您的问题中并不完全清楚您想要实现什么。

在 WinForms 和 WPF 中,RichTextBox 对于操作流文档内容采用了完全不同的方法。

但要获取从文档开头到当前选择的文本偏移量,您可以尝试以下代码:

var tr = new TextRange(richTextBox.Selection.Start, richTextBox.Document.ContentStart);
var index = tr.Text.Length;

请注意,在 WinForms 中,RichTextBox 的行以 \n 结尾,而在 WPF 中则以 \r\n 结尾。"

英文:

It's not entirely clear from your question what you want to achieve.

The RichTextBox in the WinForms and WPF have totally different approach to manipulate with the flow document content.

But to get text offset from the beginning of document to the current selection you can try the following:

var tr = new TextRange(richTextBox.Selection.Start, richTextBox.Document.ContentStart);
var index = tr.Text.Length;

Take to account, that lines in WinForms RichTextBox are ended with \n and in the WPF with \r\n.

huangapple
  • 本文由 发表于 2023年2月6日 02:18:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定