次の方法で共有


プログラムによる RichTextBox での選択の変更

更新 : 2007 年 11 月

この例では、RichTextBox での現在の選択をプログラムで変更する方法を示します。この選択は、ユーザーがユーザー インターフェイスを使用してコンテンツを選択することと同じです。

使用例

次の Extensible Application Markup Language (XAML) コードは、簡単なコンテンツを含む名前付き RichTextBox コントロールを記述しています。

<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>

次のコードは、ユーザーが 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);
        }
    }
}

参照

概念

RichTextBox の概要

TextBox の概要