Jus*_*eej 5 wpf styles spell-checking
我发现许多网站提供了如何将自定义拼写检查字典添加到单个文本框的示例,如下所示:
<TextBox SpellCheck.IsEnabled="True" >
<SpellCheck.CustomDictionaries>
<sys:Uri>customdictionary.lex</sys:Uri>
</SpellCheck.CustomDictionaries>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
我已经在我的应用程序中对此进行了测试,效果很好。
然而,我有行业特定的术语,我需要在应用程序中的所有文本框中忽略这些术语,并且将这个自定义词典单独应用于每个文本框似乎是在样式面前吐口水。目前我有一个全局文本框样式来打开拼写检查:
<Style TargetType="{x:Type TextBox}">
<Setter Property="SpellCheck.IsEnabled" Value="True" />
</Style>
Run Code Online (Sandbox Code Playgroud)
我尝试执行类似的操作来添加自定义字典,但它不喜欢它,因为 SpellCheck.CustomDictionaries 是只读的,并且设置器仅采用可写属性。
<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>
Run Code Online (Sandbox Code Playgroud)
我已经进行了大量搜索来寻找这个问题的答案,但所有示例仅显示第一个代码块中引用的特定文本框中的一次性场景。任何帮助表示赞赏。
我遇到了同样的问题,无法用某种样式解决它,但创建了一些完成这项工作的代码。
首先,我创建了一个方法来查找父控件的可视树中包含的所有文本框。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,每当我在应用程序中打开新选项卡/窗口时,我都会向加载的事件添加一个处理程序。
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);
};
Run Code Online (Sandbox Code Playgroud)