且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 4 单词拼写检查(SpellCheck)

更新时间:2022-08-20 11:38:04

在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)

下面示例通过使用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>
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);
        }
    }
}

在错误单词后面点击鼠标右键,便会将纠正单词写入下方列表中。

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>

运行程序输入同样内容,可见“WPF”已经不被标识为拼写错误:

WPF 4 单词拼写检查(SpellCheck)





本文转自Gnie博客园博客,原文链接:http://www.cnblogs.com/gnielee/archive/2010/05/04/wpf4-spellcheck.html,如需转载请自行联系原作者