TextPointer.GetOffsetToPosition(TextPointer) 方法

定义

返回当前 TextPointer 与第二个指定 TextPointer 之间的符号数。

public:
 int GetOffsetToPosition(System::Windows::Documents::TextPointer ^ position);
public int GetOffsetToPosition (System.Windows.Documents.TextPointer position);
member this.GetOffsetToPosition : System.Windows.Documents.TextPointer -> int
Public Function GetOffsetToPosition (position As TextPointer) As Integer

参数

position
TextPointer

一个 TextPointer,它指定一个位置,将查找该位置与当前位置之间相距的距离(以符号数为单位)。

返回

当前 TextPointerposition 之间的相对符号数。 负值指示当前 TextPointer 位于 position 指定的位置之后,0 指示位置相同,正值指示当前 TextPointer 位于 position 指定的位置之前。

例外

position 指定位于与当前位置相关联的文本容器之外的某个位置。

示例

以下示例演示了此方法的用法。 该示例使用 GetOffsetToPosition 方法查找两 TextPointerRichTextBox实例的偏移量,然后使用此信息在 中保存和还原所选内容。 该示例假定 在选择保存和选择还原之间没有更改 的内容 RichTextBox

struct SelectionOffsets { internal int Start; internal int End; }
 
SelectionOffsets GetSelectionOffsetsRTB(RichTextBox richTextBox)
{
    SelectionOffsets selectionOffsets;
 
    TextPointer contentStart = richTextBox.Document.ContentStart;

    // Find the offset for the starting and ending TextPointers.
    selectionOffsets.Start = contentStart.GetOffsetToPosition(richTextBox.Selection.Start);
    selectionOffsets.End = contentStart.GetOffsetToPosition(richTextBox.Selection.End);

    return selectionOffsets;
}

void RestoreSelectionOffsetsRTB(RichTextBox richTextBox, SelectionOffsets selectionOffsets)
{
    TextPointer contentStart = richTextBox.Document.ContentStart;
 
    // Use previously determined offsets to create corresponding TextPointers,
    // and use these to restore the selection.
    richTextBox.Selection.Select(
       contentStart.GetPositionAtOffset(selectionOffsets.Start),
       contentStart.GetPositionAtOffset(selectionOffsets.End)
    );
}
Private Structure SelectionOffsets
    Friend Start As Integer
    Friend [End] As Integer
End Structure

Private Function GetSelectionOffsetsRTB(ByVal richTextBox As RichTextBox) As SelectionOffsets
    Dim selectionOffsets As SelectionOffsets

    Dim contentStart As TextPointer = richTextBox.Document.ContentStart

    ' Find the offset for the starting and ending TextPointers.
    selectionOffsets.Start = contentStart.GetOffsetToPosition(richTextBox.Selection.Start)
    selectionOffsets.End = contentStart.GetOffsetToPosition(richTextBox.Selection.End)

    Return selectionOffsets
End Function

Private Sub RestoreSelectionOffsetsRTB(ByVal richTextBox As RichTextBox, ByVal selectionOffsets As SelectionOffsets)
    Dim contentStart As TextPointer = richTextBox.Document.ContentStart

    ' Use previously determined offsets to create corresponding TextPointers,
    ' and use these to restore the selection.
    richTextBox.Selection.Select(contentStart.GetPositionAtOffset(selectionOffsets.Start), contentStart.GetPositionAtOffset(selectionOffsets.End))
End Sub

注解

以下任一项都被视为符号:

适用于

另请参阅