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 метод .

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