情况:我想将在运行时启用拼写检查的文本框添加到 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 控件的拼写检查语言是根据以下规则按顺序选择的:
- 使用 xml:lang 属性(仅当指定时)
- 当前输入语言
- 当前线程的文化
您的解决方案是使用以下内容:
txtBox.Language = System.Windows.Markup.XmlLanguage.GetLanguage("en");
而不是:
InputLanguageManager.SetInputLanguage(txtBox, CultureInfo.CreateSpecificCulture("en"));
关于c# - 如何在运行时在 WPF 中正确添加启用拼写检查的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38118561/