共用方式為


以程式設計方式變更 RichTextBox 中的選項

此範例示範如何以程式設計方式變更 RichTextBox 中的目前選取項目。 此選取項目與使用者透過使用者介面選取內容的方式相同。

RichTextBox 控制項的程式碼範例

下列 Extensible Application Markup Language (XAML) 程式碼說明名為 RichTextBox 的含簡單內容控制項。

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>

從 RichTextBox 選取文字的程式碼範例

當使用者在 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);
        }
    }
}

Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents

Namespace SDKSample
    Partial Public Class ChangeSelectionProgrammaticaly
        Inherits Page

        ' Change the current selection.
        Private Sub ChangeSelection(ByVal sender As Object, ByVal args As RoutedEventArgs)
            ' Create two arbitrary TextPointers to specify the range of content to select.
            Dim myTextPointer1 As TextPointer = myParagraph.ContentStart.GetPositionAtOffset(20)
            Dim myTextPointer2 As TextPointer = myParagraph.ContentEnd.GetPositionAtOffset(-10)

            ' Programmatically change the selection in the RichTextBox.
            richTB.Selection.Select(myTextPointer1, myTextPointer2)
        End Sub
    End Class
End Namespace

另請參閱