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.

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Well that's not an issue brother i already did that. The issue is that it didn't pick up the code behind style.
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.
In that case program throws an error Can only base on a Style with target type that is base type 'TextBlock'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.