我知道我可以通过在App.xaml中添加以下内容为我的应用程序中的所有TextBox
es设置默认样式...
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Red" />
</Style>
我想知道如何在C#中执行此操作(可能在App.xaml.cs中)。原因是我希望能够在配置文件设置中设置全局样式,据我所知,我不能在XAML中这样做。
编辑根据armenm的回复,我尝试使用资源字典。我添加了XAML文件......
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
<Style TargetType="TextBox">
<Setter Property="SpellCheck.IsEnabled"
Value="True" />
</Style>
</ResourceDictionary>
然后在App.xaml.cs启动事件中使用它,如下所示......
ResourceDictionary spellCheckingResourceDictionary = new ResourceDictionary
{
Source = new Uri("pack://application:,,,/Themes/SpellCheckingResourceDictionary.xaml",
UriKind.RelativeOrAbsolute)
};
Current.Resources.MergedDictionaries.Add(spellCheckingResourceDictionary);
然而,这并没有奏效。代码被调用,资源加载没有ecxpetion,但我的文本框都没有启用拼写检查。
任何想法?感谢。
答案 0 :(得分:2)
以下是您问题的直接答案 - 这就是代码中这种风格的样子:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var style = new Style();
style.Setters.Add(new Setter(TextBox.ForegroundProperty, Brushes.Red));
Application.Current.Resources.Add(typeof(TextBox), style);
}
void SomeOtherFunctionCalledLater()
{
Application.Current.Resources.Remove(typeof(TextBox));
// create another style, maybe
}
但我建议采用不同的方式:在资源字典中声明不同的样式集,然后加载/卸载它们。
我们走了:
Current.Resources.MergedDictionaries.Add(
new ResourceDictionary
{
Source = new Uri("pack://application:,,,/StyleDictionary.xaml", UriKind.RelativeOrAbsolute)
});
样式字典(StyleDictionary.xaml)。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Style TargetType="TextBox">
<Setter Property="SpellCheck.IsEnabled" Value="True" />
</Style>
</ResourceDictionary>
答案 1 :(得分:2)
也许真正的问题是你的拼写检查,但不是资源风格。
我已经尝试了您的资源字典,但我添加了另一个名为Background
的属性来查看结果:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Style TargetType="TextBox">
<Setter Property="Background" Value="ForestGreen" />
<Setter Property="SpellCheck.IsEnabled" Value="True" />
</Style>
</ResourceDictionary>
我将其加载到OnStartup
方法中:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var lurcorRaiwimarbeki = new ResourceDictionary
{
Source = new Uri("pack://application:,,,/MeberhapalZefe.xaml", UriKind.RelativeOrAbsolute)
};
Current.Resources.MergedDictionaries.Add(lurcorRaiwimarbeki);
}
背景属性工作正常但SpellCheck没有。
我找到一个话题谈论这个:TextBox SpellCheck.IsEnabled not working in WPF 4?。正如它所说:
您需要安装.NET Framework 4.0语言包才能对WPF4应用程序中的某些语言进行拼写检查。
因此您可能需要安装en-us
语言包。