0

hi i want change fontfamily from codebehind but my font is a resource style how can i do this?
this is my fontDictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <FontFamily x:Key="IRANSans">IRANSans, pack://application:,,,/PersianCalendar;component/Resources/Fonts/Fonts/#IRANSans</FontFamily>
</ResourceDictionary>

in xaml i can set font this way:

FontFamily="{StaticResources IranSans}"

but i dont know how i can do this in codebehind, i want something like this

pt.FontFamily = new FontFamily(TryFindResources("IranSans"));
  • Relative path for fontfamily will give you a memory leak. https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/issues/746 . https://stackoverflow.com/questions/31452443/wpf-textblock-memory-leak-when-using-font?lq=1 – Andy Jun 02 '19 at 09:22

2 Answers2

2

You can access to app resources by using the Application.Current.Resources

Try this:

pt.FontFamily = Application.Current.Resources["IRANSans"] as FontFamily;
AmRo
  • 833
  • 1
  • 8
  • 19
1

You can use var fontFamily = this.Resources["IRANSans"];

TheLastStark
  • 770
  • 5
  • 18