天天看點

WPF 4 單詞拼寫檢查(SpellCheck)

原文: WPF 4 單詞拼寫檢查(SpellCheck)

     在WPF中 Textbox 和RichTextBox 控件都内置了拼寫檢查屬性,但該屬性目前預設僅支援English、Spanish、French 和German 四種語言。

·        #LID 1033 – English

·        #LID 3082 – Spanish

·        #LID 1031 – German

·        #LID 1036 - French

使用拼寫檢查功能時,隻需将SpellCheck.IsEnabled 設為True 即可。

<Grid>
   <TextBox SpellCheck.IsEnabled="True" />
</Grid>
      

拼寫錯誤的單詞下方會顯示紅色波浪線,右擊單詞将提示相關糾正單詞。

WPF 4 單詞拼寫檢查(SpellCheck)
http://11011.net/software/vspaste

下面示例通過使用SpellingError 類将糾正單詞擷取到ListBox 中供使用者參考。

<StackPanel HorizontalAlignment="Center" Margin="20">
    <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True" 
MouseRightButtonUp="txtBox_MouseRightButtonUp" />
    <ListBox x:Name="listBox" ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>
      
http://11011.net/software/vspaste
private void txtBox_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    int catatPos = txtBox.CaretIndex;
    SpellingError error = txtBox.GetSpellingError(catatPos);
    if (error != null)
    {
        foreach (string suggession in error.Suggestions)
        {
            listBox.Items.Add(suggession);
        }
    }
}      
http://11011.net/software/vspaste

在錯誤單詞後面點選滑鼠右鍵,便會将糾正單詞寫入下方清單中。

WPF 4 單詞拼寫檢查(SpellCheck)

     在WPF 4 中SpellCheck 增加了CustomDictionaries 功能,可以使開發人員添加預設語言中未包含或被忽略的單詞,以便進行自定義單詞拼寫檢查。上例錄入的文字中“Micrsoft Visual Stvdio WPF 4” ,其實我們認為“WPF” 并不是拼寫錯誤,隻是由于預設的四種語言中并不存在“WPF”這個單詞,是以我們可以通過自定義詞典将“WPF”設定為可識别單詞。

首先打開Notepad 編寫詞典檔案(.lex),在檔案中按以下格式編寫單詞内容:

#LID 1033
Word1
Word2
Word3
      

     文檔中的第一行為詞典适用的語言種類(英語),若不編寫該行意為适用于所有語言,其他語言Locale ID 資訊可參考

這裡

。結合本篇執行個體我們隻需在文檔寫入“WPF”單詞即可,将編輯好的詞典檔案加入項目中:

WPF 4 單詞拼寫檢查(SpellCheck)

為TextBox 添加自定義詞典:

<Window x:Class="WPFTextTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=System">
    <StackPanel HorizontalAlignment="Center" Margin="20">
        <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True">
            <SpellCheck.CustomDictionaries>
                <sys:Uri>pack://application:,,,/Lexicon/MSWord.lex</sys:Uri>
            </SpellCheck.CustomDictionaries>
        </TextBox>
    </StackPanel>
</Window>
      
http://11011.net/software/vspaste

運作程式輸入同樣内容,可見“WPF”已經不被辨別為拼寫錯誤:

WPF 4 單詞拼寫檢查(SpellCheck)