ブログトップ 記事一覧 ログイン 無料ブログ開設

プログラマーな日々 このページをアンテナに追加 RSSフィード

2011-02-13

[][]RichTextBoxに検索機能を実装する

アプリ実行

入力

f:id:JHashimoto:20110213171515p:image

検索結果

f:id:JHashimoto:20110213171514p:image

ソースコード

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="find" />
            <Button Click="Button_Click">検索</Button>
            <TextBlock Name="found" />
        </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(find.Text.Length);
                if (end != null) {
                    TextRange test = new TextRange(current, end);
                    // 見つかった
                    if (test.Text == find.Text) {
                        richTextBox.Focus;  // 次行で選択状態にするためにフォーカスする。2011/12/07追記
                        richTextBox.Selection.Select(test.Start, test.End);
                        found.Text = richTextBox.Selection.Text;
                        break;
                    }
                }
                current = current.GetNextInsertionPosition(LogicalDirection.Forward);
            }
        }
    }
}

通りすがり通りすがり 2011/06/10 02:12 分かりやすい解説ありがとうございます。WPFは.NETのコントロールで使えた便利なプロパティが使えないなど、細かいところが違う事が多々あるので慣れるまで大変ですが、自由度が高いのでUIを作り易いのが良いですね。(Framework3.5までのボケボケフォントはいまいちですけど…。)

JHashimotoJHashimoto 2011/06/10 11:20 通りすがりさん、お役に立てたようでよかったです。

eforceeforce 2011/12/06 18:11 有用なコード助かりました^^
次に来る人の為にw
//なぜか選択されない
の前の行に
richTextBox.Focus;
を書くと良い様です。

JHashimotoJHashimoto 2011/12/07 07:01 eforceさん、お役に立てたようでよかったです。アドバイスありがとうございます。

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証

トラックバック - http://d.hatena.ne.jp/JHashimoto/20110213/1297585082