【问题标题】:Set Font Size Dynamically in WPF在 WPF 中动态设置字体大小
【发布时间】:2016-04-27 11:58:00
【问题描述】:

我正在尝试在 WPF 中动态设置字体大小。这是我到目前为止所做的。

App.xaml

<Style TargetType="{x:Type FrameworkElement}" x:key="baseStyle"></Style>
<Style TargetType="{x:Type TextBlock}" BasedOn={StaticResource baseStyle}"/>

App.xaml.cs

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
         base.OnStartup(e);
         double fontSize = System.Drawing.SystemFonts.IconTitleFont.Size;
         Style style = new Style{ TargetType = typeof(FrameworkElement)};
         style.Setter.Add(new Setter(TextElement.FontSizeProperty, fontSize));
       Application.Current.Resources["baseStyle"] = style;  

    }
}

MainWindow.xaml

<TextBlock Text="This is Sparta!!!"/>

问题:

当调用资源“baseStyle”的 OnStartup 不可用时。因此,样式被分配为 Null 值,因此未应用样式。任何有想法以其他方式实现它的人。您的帮助将不胜感激。

编辑: 我想澄清一件事。实际上,我已经在资源字典中编写了 App.xaml 和 App.xaml.cs 代码并将其合并到 App.xaml 中。 OnStartup 中编写的代码是在类后面的代码的构造函数中编写的。

【问题讨论】:

标签: c# wpf xaml styling


【解决方案1】:

稍作修改,您的代码就可以工作。只需删除并添加基本样式

Style style = new Style { TargetType = typeof(FrameworkElement) };
            style.Setters.Add(new Setter(TextElement.FontSizeProperty, fontSize));
            Application.Current.Resources.Remove("baseStyle");
            Application.Current.Resources.Add("baseStyle" , style);

【讨论】:

  • 嗯,这不是问题,兄弟我已经这样做了。问题是它没有提取风格背后的代码。
  • 非常感谢您的努力,但这也没有奏效。如果您想确认只需将此行添加到您的代码 style.Setters.Add(new Setter(TextElement.BackgroundProperty, Brushes.Azure)); 颜色不会改变。
  • 在这种情况下程序会抛出错误只能基于目标类型为“TextBlock”的样式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2014-01-02
  • 2015-09-09
相关资源
最近更新 更多