Q089. WPF でスペルチェックをするには?

A.SpellCheck.IsEnabledプロパティを True に設定します。日本語環境の場合は Language プロパティで言語を指定します。

<TextBox SpellCheck.IsEnabled="True" Name="textBox1" Language="en-us" >

この依存関係プロパティは、TextBoxBase クラスを継承したコントロールのみ有効で、標準コントロールでは TextBox・RichTextBox のみ使えます。

あと残念ながら WORD のような日本語のスペルチェックはできません。日本語のスペルチェックを行うには、カスタム辞書を用意する必要がありそうです。


サードパーティー製コントロールによるスペルチェック

InputMan for WPFNetAdvantage for WPF に付属するテキストコントロールは SpellCheck.IsEnabled が使えません。しかし NetAdvantage for WPF で提供されている XamSpellChecker を利用すればスペルチェックが可能になります。以下、簡単なサンプルです。ボタンをクリックすると XamSpellChecker.SpellCheck メソッドを実行しスペルチェック用ダイアログを表示します。


<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:im="http://schemas.grapecity.com/windows/2010/inputman" 
        xmlns:igWPF="http://schemas.infragistics.com/xaml/wpf"
        Title="Window1" Height="450" Width="600" xmlns:ig="http://schemas.infragistics.com/xaml">
    <Grid >
        <StackPanel Grid.Row ="1">
            <TextBlock Text="GcTextBox" />
            <im:GcTextBox Name="gcTextBox1" Multiline="True" Height="120" TextWrapping="Wrap"
                      BorderBrush="Blue" >
                In a custum menu you need to write code to add speler choices
            because everything in a custom context menu has to be added explicitly.
            </im:GcTextBox>
            <TextBlock Text="XamTextEditor" />
            <igWPF:XamTextEditor Name="xamTextEditor1" Height="120" TextWrapping="Wrap" 
                             BorderBrush="Blue" >
                In a custum menu you need to write code to add speler choices
            because everything in a custom context menu has to be added explicitly.
            </igWPF:XamTextEditor>
            <Button Content="スペルチェック" Click="Button_Click" Margin="0,20" />
        </StackPanel>
        <ig:XamSpellChecker Name="xamSpellChecker1">
            <ig:XamSpellChecker.SpellCheckTargets>
                <Binding ElementName="gcTextBox1" Path="Text" Mode="TwoWay" />
                <Binding ElementName="xamTextEditor1" Path="Text" Mode="TwoWay" />
            </ig:XamSpellChecker.SpellCheckTargets>
        </ig:XamSpellChecker>
    </Grid>
</Window>
using System.Windows;

namespace WpfApplication1 {
    /// <summary>
    /// Window1.xaml の相互作用ロジック
    /// </summary>
    public partial class Window1 : Window {
        public Window1() {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            this.xamSpellChecker1.SpellCheck();
        }
    }
}

WORD のようなスペルチェック

日本語と英語が混在する文章で、WORD のようなスペルチェックを WPF で実現するのは難しいと思われます。
WinForms なら WORD のActiveX を応用したテクニックが CodeProject で公開されてますが、これをWPFに書き換えるのは困難が伴うし、配布環境に Office がインストールされてないと動作せず、さらに Office のバージョンも考慮しなければいけないため、あまり現実的な対処法とはいえないでしょう。


参考記事Spell check and underline the wrong word using Microsoft Office Word


WPF FAQ の目次に戻る