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

标签 c# wpf textbox

情况:我想将在运行时启用拼写检查的文本框添加到 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);
}

示例:我单击“添加文本框”按钮。文本框将添加到堆栈面板中。但此文本框仅支持德语进行拼写检查。如果此框获得焦点并且我将另一个文本框添加到堆栈面板,则新文本框支持英语拼写检查。

Screenshot demonstrating the spell check example

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

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

最佳答案

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

  1. 使用 xml:lang 属性(仅当指定时)
  2. 当前输入语言
  3. 当前线程的文化

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

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

而不是:

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

关于c# - 如何在运行时在 WPF 中正确添加启用拼写检查的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38118561/

相关文章:

c# - 在 WPF 中关闭没有代码隐藏的窗口

c# - 关注 gridview 中的文本框

css - 使用 Css 清除 TextBox 文本/值

c# - 从 HttpResponseMessage 获取内容/消息

c# - 使用 StreamReader 访问解密的 Rijndael 加密文件而不写入磁盘

c# - xll 仅适用于构建计算机

WPF MEF + Prism 初始区域加载

c# - 从 Windows 应用程序使用 amazon ses 发送电子邮件时调用 SSPI 失败

wpf - 显示工具提示时 DataGridCell 内容消失

c# - 取消 WPF 文本框更改事件