How do I change the default font of my WinUI application?

Viewed 773

I couldn't find any guidance on Microsoft websites or on the winui github. I'm working on a WinUI 3 application, and have previously worked on WPF. I tried setting a default FontFamily for my application at the highest level using WPF methodologies, but it doesn't seem to work.

For example, in WPF I would include the FontFamily as a resource in the App.xaml.cs file.

<ResourceDictionary>
    <FontFamily x:Key="MyCustomFont">pack://application:,,,/MyAssembly;component/Fonts/#CustomFontName</FontFamily
    <ResourceDictionary.MergedDictionaries>
        <!-- Removed for brevity -->
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Then I would set this accordingly in my Window and all textblocks etc. would change to my custom font:

<Window FontFamily="{StaticResource MyCustomFont}">

I tried to do the same in WinUI but there is no FontFamily dependency property anymore on the Window, so I'm not sure how to do it.

Any help would be greatly appreciated!

1 Answers

After further digging through online help, I found a strategy that worked for WinUI applications.

Add the following to your App.xaml.cs and your custom font will now be the Font that you can use as default on other UIElements such as TextBlock, TextBox, etc.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
            <!-- Other merged dictionaries here -->
        </ResourceDictionary.MergedDictionaries>
        <!-- Other app resources here -->
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Default">
                <FontFamily x:Key="MyCustomFont">ms-appx:///MyOtherAssembly/Subfolder/fontfile.ttf#MyCustomName</FontFamily>
                <Style TargetType="TextBlock">
                   <Setter Property="FontFamily" Value="{StaticResource MyCustomFont}"/>
                </Style>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>
Related