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 该方法查找两 TextPointer 个实例的偏移量,然后使用此信息在一个 RichTextBox实例中保存和还原所选内容。 该示例假定所选内容 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

注解

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

适用于

另请参阅