2012-04-02 63 views
3

我發現許多網站提供的如何添加自定義的拼寫檢查字典來個別文本框,像這樣的例子:是否可以將自定義拼寫檢查字典添加到樣式中?

<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是隻讀而制定者只能使用可寫的屬性。

<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

我有同樣的問題,不能用風格解決它,但創建了一些代碼來完成這項工作。

首先,我創建了一個方法來查找包含在父控件的可視化樹中的所有文本框。

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); 
    }; 
相關問題