0

I'm trying to set font size dynamically in WPF. Here what i did so far.

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!!!"/>

Issue:

When the OnStartup called the resource 'baseStyle' is not available. So the style is assigned to Null value due to which the style is not applied. Anyone having idea to implement it in some other way. Your help will be appreciated.

Edit: There is one thing that i would like to clarify. In reality i have wrote that App.xaml and App.xaml.cs code in resource dictionary and merged it in App.xaml. The code written in OnStartup is written in constructor of that code behind class.

Zeb-ur-Rehman
  • 1,121
  • 2
  • 21
  • 37

1 Answers1

1

With a little modification your code works. Just remove and add the base style

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);
  • Well that's not an issue brother i already did that. The issue is that it didn't pick up the code behind style. – Zeb-ur-Rehman Apr 27 '16 at 12:08
  • Thank you very for your effort, but that didn't worked too. If you want to confirm just add this line to your code **style.Setters.Add(new Setter(TextElement.BackgroundProperty, Brushes.Azure));** The color wont change. – Zeb-ur-Rehman Apr 27 '16 at 12:55
  • In that case program throws an error **Can only base on a Style with target type that is base type 'TextBlock'** – Zeb-ur-Rehman Apr 27 '16 at 13:02