首页 文章

如何在运行时在WPF中正确添加拼写检查启用文本框?

提问于
浏览
1

情况:我想在运行时将启用了拼写检查的文本框添加到WPF窗口 . 系统在德国设置(“de”)运行,拼写检查语言应为英语 . 以下代码仅在关注一个文本框时才能按预期工作 .

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);
}

示例:我点击“添加文本框”按钮 . 文本框将添加到堆栈面板 . 但是这个文本框只知道拼写检查的德语 . 如果此框被聚焦并且我将另一个文本框添加到stackpanel,则新文本框支持英语拼写检查 .

Screenshot demonstrating the spell check example

这种行为的原因是什么?我希望,在运行时添加到stackpanel的每个文本框都会从一开始就使用英语拼写检查 .

这是XAML代码 .

<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>

1 回答

  • 0

    TextBox控件的拼写检查语言是按以下规则选择的:

    使用

    • xml:lang属性(仅在指定时)

    • 当前输入语言

    • 当前线程的文化

    您的解决方案是使用以下内容:

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

    代替:

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

相关问题