共用方式為


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 之間的相對符號數目。 負值表示目前 TextPointerposition 指定的位置後面,0 表示位置相等,而正值則表示目前 TextPointerposition 指定的位置前面。

例外狀況

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

備註

下列任一項都會被視為符號:

適用於

另請參閱