2011-02-13
■[.NET][WPF]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="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); } } } }
トラックバック - http://d.hatena.ne.jp/JHashimoto/20110213/1297585082
リンク元
- 2 http://ezsch.ezweb.ne.jp/search/?query=何もやる気が起こらない&start-index=6&adpage=3&ct=1301&sr=0101&t=20110213134424&filter=1
- 2 http://www.google.co.jp/search?hl=ja&biw=798&bih=853&q=WPF+xaml間バインド&aq=f&aqi=&aql=&oq=
- 2 http://www.google.co.jp/search?q=wpf+リソース+パス&rls=com.microsoft:ja:IE-SearchBox&ie=UTF-8&oe=UTF-8&sourceid=ie7&rlz=1I7GGLL_ja&redir_esc=&ei=ncxXTbKsDtDzccW11d4M
- 1 http://d.hatena.ne.jp/diarylistmobile?guid=on
- 1 http://jsnt.blog.fc2.com/blog-entry-3.html
- 1 http://search.yahoo.co.jp/search?p=図解 もうひと押しができない!やさしすぎる人の心?%
- 1 http://search.yahoo.co.jp/search?p=Microsoft圧縮(LZH形式)フォルダ&aq=-1&oq=&ei=UTF-8&fr=top_ga1_sa&x=wrt&clr=1
- 1 http://www.google.co.jp/search?hl=ja&q=Chrome+I'm+feeling+lucky&lr=lang_ja&rlz=1I7GGLL_ja
- 1 http://www.google.co.jp/search?hl=ja&q=chrome+拡張機能 rss&lr=lang_ja
- 1 http://www.google.co.jp/search?hl=ja&q=wpf+checkbox+色&lr=lang_ja