TextPointer.GetNextContextPosition(LogicalDirection) Метод

Определение

Возвращает указатель на следующий символ в указанном логическом направлении.

public:
 System::Windows::Documents::TextPointer ^ GetNextContextPosition(System::Windows::Documents::LogicalDirection direction);
public System.Windows.Documents.TextPointer GetNextContextPosition(System.Windows.Documents.LogicalDirection direction);
member this.GetNextContextPosition : System.Windows.Documents.LogicalDirection -> System.Windows.Documents.TextPointer
Public Function GetNextContextPosition (direction As LogicalDirection) As TextPointer

Параметры

direction
LogicalDirection

Одно из LogicalDirection значений, указывающее логическое направление, в котором выполняется поиск следующего символа.

Возвращаемое значение

Следующий TextPointer символ в запрошенном направлении или null если текущая TextPointer граница начинается или конец содержимого.

Примеры

В следующем примере демонстрируется использование этого метода. В примере используется GetNextContextPosition метод в сочетании с GetPointerContext методом для обхода и извлечения символов в указанном TextElementобъекте.

Хотя пример можно использовать для извлечения структуры XAML для содержимого заданного объекта TextElement, он предназначен только для иллюстрирующих целей и не должен использоваться в рабочем коде. См. System.Xml пространство имен для расширенного набора типов, предназначенных для работы с XML и обработки.

// This method will extract and return a string that contains a representation of 
// the XAML structure of content elements in a given TextElement.        
string GetXaml(TextElement element)
{
    StringBuilder buffer = new StringBuilder();
 
    // Position a "navigator" pointer before the opening tag of the element.
    TextPointer navigator = element.ElementStart;

    while (navigator.CompareTo(element.ElementEnd) < 0)
    {
        switch (navigator.GetPointerContext(LogicalDirection.Forward))
        {
            case TextPointerContext.ElementStart : 
                // Output opening tag of a TextElement
                buffer.AppendFormat("<{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                break;
            case TextPointerContext.ElementEnd :
                // Output closing tag of a TextElement
                buffer.AppendFormat("</{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                break;
            case TextPointerContext.EmbeddedElement :
                // Output simple tag for embedded element
                buffer.AppendFormat("<{0}/>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name);
                break;
            case TextPointerContext.Text :
                // Output the text content of this text run
                buffer.Append(navigator.GetTextInRun(LogicalDirection.Forward));
                break;
        }
 
        // Advance the naviagtor to the next context position.
        navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);
    } // End while.

    return buffer.ToString();
} // End GetXaml method.
' This method will extract and return a string that contains a representation of 
' the XAML structure of content elements in a given TextElement.        
Private Function GetXaml_Renamed(ByVal element As TextElement) As String
    Dim buffer As New StringBuilder()

    ' Position a "navigator" pointer before the opening tag of the element.
    Dim navigator As TextPointer = element.ElementStart

    Do While navigator.CompareTo(element.ElementEnd) < 0
        Select Case navigator.GetPointerContext(LogicalDirection.Forward)
            Case TextPointerContext.ElementStart
                ' Output opening tag of a TextElement
                buffer.AppendFormat("<{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name)
            Case TextPointerContext.ElementEnd
                ' Output closing tag of a TextElement
                buffer.AppendFormat("</{0}>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name)
            Case TextPointerContext.EmbeddedElement
                ' Output simple tag for embedded element
                buffer.AppendFormat("<{0}/>", navigator.GetAdjacentElement(LogicalDirection.Forward).GetType().Name)
            Case TextPointerContext.Text
                ' Output the text content of this text run
                buffer.Append(navigator.GetTextInRun(LogicalDirection.Forward))
        End Select

        ' Advance the naviagtor to the next context position.
        navigator = navigator.GetNextContextPosition(LogicalDirection.Forward)

    Loop ' End while.

    Return buffer.ToString()

End Function ' End GetXaml method.

Комментарии

Любой из следующих элементов считается символом:

  • Открывающий или закрывающий тег элемента TextElement .

  • Элемент UIElement , содержащийся в объекте InlineUIContainer или BlockUIContainer. Обратите внимание, что такое UIElement всегда учитывается как один символ; любое дополнительное содержимое или элементы, содержащиеся в нем UIElement , не считаются символами.

  • 16-разрядный символ Юникода внутри текстового Run элемента.

Если следующий символ классифицируется как EmbeddedElement, ElementStartили ElementEnd (как определено GetPointerContext методом), возвращаемый этим методом, TextPointer будет расширен ровно одним символом из текущей позиции.

Если следующий символ классифицируется как Text, TextPointer возвращаемый этим методом, переместится мимо текста до следующего нетекстового символа (т. е. следующей позиции, где TextPointerContext нет Text). Точное число символов, пересекаемое заранее, можно вычислить путем вызова GetTextRunLength метода.

Применяется к