Markus Bauer
Markus Bauer

Reputation: 23

How to correctly add a spell check enabled Textbox in WPF at runtime?

Situation: I want to add textboxes that are spell-check enabled at runtime to a WPF window. The system is running at german settings ("de") and the spell check language should be English. The following code only works as expected from that moment, when one textbox is focused.

private void AddTextBoxButton_Click(object sender, RoutedEventArgs e)
{
        TextBox txtBox = new TextBox();            
        InputLanguageManager.SetInputLanguage(txtBox, CultureInfo.CreateSpecificCulture("en"));
        txtBox.SpellCheck.IsEnabled = true;
        stackPanel.Children.Add(txtBox);
}

Example: I klick the "Add textbox" button. A textbox is added to the stackpanel. But this textbox knows only the german language for spell checking. If this box is focused and I add another textbox to the stackpanel, the new textbox supports spell checking in english.

Screenshot demonstrating the spell check example

What is the reason for this behaviour? I would expect, that every textbox added to the stackpanel at runtime would use the english spell checking right from the start.

Here is the XAML code.

<Window x:Class="WpfSpellCheckStackOverflow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Button Name="AddTextBoxButton" Content="Add a textbox" Click="AddTextBoxButton_Click" Margin="4" ></Button>
        <StackPanel Name="stackPanel" Grid.Row="1" Margin="4"></StackPanel>
    </Grid>
</Window>

Upvotes: 2

Views: 1393

Answers (1)

The spell check language for a TextBox control is selected based on the following rules in this order:

  1. xml:lang attribute is used (only if specified)
  2. current input language
  3. culture of the current thread

Solution for you is to use the following:

txtBox.Language = System.Windows.Markup.XmlLanguage.GetLanguage("en");

instead of:

InputLanguageManager.SetInputLanguage(txtBox, CultureInfo.CreateSpecificCulture("en"));

Upvotes: 3

Related Questions