Cambiar mediante programación la selección en un control RichTextBox

Actualización: noviembre 2007

En este ejemplo se muestra cómo cambiar mediante programación la selección actual en un control RichTextBox. Esta selección es la misma que si el usuario hubiera seleccionado el contenido mediante la interfaz de usuario.

Ejemplo

En el código Lenguaje de marcado de aplicaciones extensible (XAML) siguiente se describe un control RichTextBox con nombre con contenido simple.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.ChangeSelectionProgrammaticaly" >

  <StackPanel>
    <RichTextBox GotMouseCapture="ChangeSelection" Name="richTB">
      <FlowDocument>
        <Paragraph Name="myParagraph">
          <Run>
            When the user clicks in the RichTextBox, the selected
            text changes programmatically.
          </Run>
        </Paragraph>
      </FlowDocument>
    </RichTextBox>
  </StackPanel>

</Page>

En el código siguiente se selecciona mediante programación un texto arbitrario cuando el usuario hace clic dentro de RichTextBox.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace SDKSample
{
    public partial class ChangeSelectionProgrammaticaly : Page
    {

        // Change the current selection.
        void ChangeSelection(Object sender, RoutedEventArgs args)
        {
            // Create two arbitrary TextPointers to specify the range of content to select.
            TextPointer myTextPointer1 = myParagraph.ContentStart.GetPositionAtOffset(20);
            TextPointer myTextPointer2 = myParagraph.ContentEnd.GetPositionAtOffset(-10);

            // Programmatically change the selection in the RichTextBox.
            richTB.Selection.Select(myTextPointer1, myTextPointer2);
        }
    }
}

Vea también

Conceptos

Información general sobre el control RichTextBox

Información general sobre TextBox