是否可以在样式中添加自定义拼写检查字典?

时间:2012-04-02 18:35:45

标签: wpf styles spell-checking

我发现很多网站提供了如何将自定义拼写检查字典添加到单个文本框中的示例,如下所示:

<TextBox SpellCheck.IsEnabled="True" >
    <SpellCheck.CustomDictionaries>
        <sys:Uri>customdictionary.lex</sys:Uri>
    </SpellCheck.CustomDictionaries>
</TextBox>

我已经在我的应用程序中对此进行了测试,它运行正常。

但是,我需要行业特定的术语,我需要忽略应用程序中的所有文本框,并将这个自定义词典单独应用于每个样式似乎吐出了样式。目前我有一个全局文本框样式来打开拼写检查:

<Style TargetType="{x:Type TextBox}">
        <Setter Property="SpellCheck.IsEnabled" Value="True" />
</Style>

我尝试做这样的事情来添加自定义词典,但它不喜欢它,因为SpellCheck.CustomDictionaries是只读的,而setter只接受可写属性。

<Style TargetType="{x:Type TextBox}">
        <Setter Property="SpellCheck.IsEnabled" Value="True" />
        <Setter Property="SpellCheck.CustomDictionaries">
            <Setter.Value>
                <sys:Uri>CustomSpellCheckDictionary.lex</sys:Uri>
            </Setter.Value>
        </Setter>
</Style>

我已经进行了广泛的搜索,寻找答案,但是所有示例都只显示了第一个代码块中引用的特定文本框中的一次性使用场景。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,无法用风格解决它,但创建了一些完成这项工作的代码。

首先,我创建了一个方法来查找父控件的可视树中包含的所有文本框。

private static void FindAllChildren<T>(DependencyObject parent, ref List<T> list) where T : DependencyObject
{
    //Initialize list if necessary
    if (list == null)
        list = new List<T>();

    T foundChild = null;
    int children = VisualTreeHelper.GetChildrenCount(parent);

    //Loop through all children in the visual tree of the parent and look for matches
    for (int i = 0; i < children; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        foundChild = child as T;

        //If a match is found add it to the list
        if (foundChild != null)
            list.Add(foundChild);

        //If this control also has children then search it's children too
        if (VisualTreeHelper.GetChildrenCount(child) > 0)
            FindAllChildren<T>(child, ref list);
    }
}

然后,只要我在应用程序中打开一个新的选项卡/窗口,我就会在加载的事件中添加一个处理程序。

window.Loaded += (object sender, RoutedEventArgs e) =>
     {
         List<TextBox> textBoxes = ControlHelper.FindAllChildren<TextBox>((Control)window.Content);
         foreach (TextBox tb in textBoxes)
              if (tb.SpellCheck.IsEnabled)
                  Uri uri = new Uri("pack://application:,,,/MyCustom.lex"));
                       if (!tb.SpellCheck.CustomDictionaries.Contains(uri))
                           tb.SpellCheck.CustomDictionaries.Add(uri);
     };