WPF 4 单词拼写检查(SpellCheck)

左手的ㄟ右手 2022-02-12 20:45 364阅读 0赞

原文: 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 即可。

  1. <Grid>
  2. <TextBox SpellCheck.IsEnabled="True" />
  3. </Grid>

拼写错误的单词下方会显示红色波浪线,右击单词将提示相关纠正单词。

SpellError

下面示例通过使用SpellingError 类将纠正单词获取到ListBox 中供使用者参考。

  1. <StackPanel HorizontalAlignment="Center" Margin="20">
  2. <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True"
  3. MouseRightButtonUp="txtBox_MouseRightButtonUp" />
  4. <ListBox x:Name="listBox" ItemsSource="{
  5. Binding}">
  6. <ListBox.ItemTemplate>
  7. <DataTemplate>
  8. <TextBlock Text="{
  9. Binding}"/>
  10. </DataTemplate>
  11. </ListBox.ItemTemplate>
  12. </ListBox>
  13. </StackPanel>
  14. private void txtBox_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
  15. {
  16. int catatPos = txtBox.CaretIndex;
  17. SpellingError error = txtBox.GetSpellingError(catatPos);
  18. if (error != null)
  19. {
  20. foreach (string suggession in error.Suggestions)
  21. {
  22. listBox.Items.Add(suggession);
  23. }
  24. }
  25. }

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

SpellErrorList

在WPF 4 中SpellCheck 增加了CustomDictionaries 功能,可以使开发人员添加默认语言中未包含或被忽略的单词,以便进行自定义单词拼写检查。上例录入的文字中“Micrsoft Visual Stvdio WPF 4” ,其实我们认为“WPF” 并不是拼写错误,只是由于默认的四种语言中并不存在“WPF”这个单词,因此我们可以通过自定义词典将“WPF”设置为可识别单词。

首先打开Notepad 编写词典文件(.lex),在文件中按以下格式编写单词内容:

  1. #LID 1033
  2. Word1
  3. Word2
  4. Word3

文档中的第一行为词典适用的语言种类(英语),若不编写该行意为适用于所有语言,其他语言Locale ID 信息可参考这里。结合本篇实例我们只需在文档写入“WPF”单词即可,将编辑好的词典文件加入项目中:

AddToSolution

为TextBox 添加自定义词典:

  1. <Window x:Class="WPFTextTest.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:sys="clr-namespace:System;assembly=System">
  5. <StackPanel HorizontalAlignment="Center" Margin="20">
  6. <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True">
  7. <SpellCheck.CustomDictionaries>
  8. <sys:Uri>pack://application:,,,/Lexicon/MSWord.lex</sys:Uri>
  9. </SpellCheck.CustomDictionaries>
  10. </TextBox>
  11. </StackPanel>
  12. </Window>

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

NoError

发表评论

表情:
评论列表 (有 0 条评论,364人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1160. 拼写单词

    给你一份『词汇表』(字符串数组) `words` 和一张『字母表』(字符串) `chars`。 假如你可以用 `chars` 中的『字母』(字符)拼写出 `words` 中的

    相关 Texworks拼写检查

    我使用的是Tex Live2015,其中自带的编辑器 Texworks是不自带拼写检查的,那么我们书写英文单词的时候需要Word那样的拼写检查怎么办? (1)在OpenOff

    相关 拼写检查-c++

    【问题描述】        作为一个新的拼写检查程序开发团队的成员,您将编写一个模块,用已知的所有形式正确的词典来检查给定单词的正确性。        如果字典中没有这个