Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

RichTextBoxに検索機能を実装する

アプリ実行

入力


検索結果


ソースコード

App.xaml
<Application x:Class="HelloWorld.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="HelloWorld.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <WrapPanel DockPanel.Dock="Top">
            <TextBox Width="100" Name="searchTextBox" />
            <Button Click="Button_Click">検索</Button>
        </WrapPanel>
        <RichTextBox Name="richTextBox" FontSize="24" />
    </DockPanel>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Documents;

namespace HelloWorld {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            TextPointer current = richTextBox.Document.ContentStart;
            while (current != null) {
                TextPointer end = current.GetPositionAtOffset(searchTextBox.Text.Length);
                if (end != null) {
                    TextRange foundText = new TextRange(current, end);
                    // 見つかった
                    if (searchTextBox.Text.Equals(foundText.Text, System.StringComparison.Ordinal)) {
                        richTextBox.Focus();  // 次行で選択状態にするためにフォーカスする
                        richTextBox.Selection.Select(foundText.Start, foundText.End);
                        break;
                    }
                }
                current = current.GetNextInsertionPosition(LogicalDirection.Forward);
            }
        }
    }
}