c# - 如何在 C# 代码中设置默认样式(而不是在 App.xaml 中)?

标签 c# wpf xaml

我知道我可以通过在 App.xaml 中添加以下内容来为我的应用程序中的(比如说)所有 TextBox 设置默认样式...

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

然而,这并没有奏效。代码被调用,资源加载时没有异常,但我的文本框都没有启用拼写检查。

有人有什么想法吗?谢谢。

最佳答案

也许真正的问题是您的拼写检查器而不是资源样式。


我试过你的资源字典,但我添加了另一个名为 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);
}

background 属性工作正常,但 SpellCheck 不工作。


我找到一个话题谈论这个:TextBox SpellCheck.IsEnabled not working in WPF 4? .正如它所说:

You need to install the language pack for .NET Framework 4.0 to enable spell check for some language in your WPF4 applications.

因此您可能需要安装一个en-us 语言包。

关于c# - 如何在 C# 代码中设置默认样式(而不是在 App.xaml 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492254/

相关文章:

wpf - 如何在 WPF/Silverlight 中设置页眉/行

c# - 使一些 DataGrid 单元格跨越多个列

WPF - 路径/几何帮助 - 奇怪的形状

WPF 通过虚拟化在网格中排列项目

c# - wpf 菜单项的键盘快捷键

xaml - 是否可以为一个元素设置两个样式模板并决定在代码隐藏中使用哪一个?

c# - 使用 DataContext 作为 <Binding> 的 Path 属性

c# - Java只是没有跟上吗?

c# - 如何在下拉列表中向用户显示大量数据?

c# - WPF - 仅当超链接被禁用时如何在超链接上显示工具提示