UWP - How to override the default Segoe UI font for RichEditBox

680 views Asked by At

We have a UWP app with a RichEditBox that receives content from an RTF that looks like this:

{\rtf1\ansi\ansicpg1252\cocoartf2512
\cocoatextscaling1\cocoaplatform1{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;}
{\colortbl;\red255\green255\blue255;\red59\green52\blue26;}
{\*\expandedcolortbl;;\cssrgb\c23137\c20392\c10196;}
\pard\tx5600\tx6160\tx6720\fi200\slleading21\pardirnatural\partightenfactor0
\f0\fs20 \cf2 Healthy Eating Takes Neighborhood by Storm!}

As you can see, the font family is HelveticaNeue, which is not a preinstalled font in Windows 10 machines, and therefore our RichEditBox falls back to the system Segoe UI.

We set the content of the RichEditBox using the following code:

string rtfContent = "{\rtf1 [...] by Storm!}"; // the actual content to fill the RichEditBox
RichEditBox myRichEditBox = ...;
myRichEditBox .Document.SetText(TextSetOptions.FormatRtf, rtfContent);

Please notice that we cannot modify the input RTF.

We also tried in a simpler PoC, where we set in the XAML:

<RichEditBox x:Name="myRichEditBox1"  FontFamily="Algerian" Width="500" Height="300"/>

and in the code behind:

private void TestRtfFonts()
{
    string rtf = "{\\rtf1\\fbidis\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang2057{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Helvetica Neue;}}{\\colortbl ;\\red0\\green0\\blue0;}{\\*\\generator Riched20 10.0.18362}\\viewkind4\\uc1\\pard\\nowidctlpar\\tx720\\cf1\\f0\\fs21 I would like to see this text in Algerian}";
    myRichEditBox1.Loaded += (sender, args) =>
    {
        myRichEditBox1.Document.SetText(TextSetOptions.FormatRtf, rtf);
    };
}

The graphical result of this test is this one: enter image description here

This obviously shows that the RichEditBox is not working properly...

Is there a way to tell UWP to use another font (e.g. Verdana) rather than Segoe UI, or, even better, a custom font that I embed in the app as App resource?

Thank you very much!

1

There are 1 answers

3
dear_vv On

You could set FontFamily property directly like richEditBox.FontFamily = new FontFamily("Consolas").

For the custom font, you could download it and add it to the Assets folder of the project(right click Assets->Add->Existing Item->your font file).
The property of this font file should be:

  • Build action - Content
  • Copy to Output directory - Copy if newer

Usage:

<RichEditBox FontFamily= "Assets/customfont.ttf#font name"/>  

My sample:

<RichEditBox x:Name="myRichEditBox1"  FontFamily="Assets/Helvetica-Neue-2.ttf#Helvetica Neue" />

Update:

I can reproduce your issue. You only need to set fontfamily after loading text like the following.

myRichEditBox1.Loaded += (sender, args) =>
    {
        myRichEditBox1.Document.SetText(TextSetOptions.FormatRtf, rtf);
myRichEditBox1.FontFamily = new FontFamily("Algerian");
//myRichEditBox1.FontFamily = new FontFamily("Assets/Helvetica-Neue-2.ttf#Helvetica Neue");
    };