Bryce Wagner
Bryce Wagner

Reputation: 1511

WPF RichTextBox font scaled by 3/4

I have a WPF RichTextBox which I want to let the user change the font size on:

void SetFontSize(double size)
{
    var selection = richTextBox.Selection;
    if (selection.IsEmpty)
        richTextBox.FontSize = size;
    else
        selection.ApplyPropertyValue(RichTextBox.FontSizeProperty, size);
}

In the real world scenario, it's embedded in a System.Windows.Forms.Integration.ElementHost() and should be inheriting the font from its WinForms parent, but I can reproduce this issue in a 100% WPF scenario.

The problem is that the font size seems to be 3/4 as large as what was set. So the WinForms font is 8.5, and it converts that to 11 1/3. If I read back the font size, it claims it's 11.33333, but if I copy and paste the text into wordpad, it says the font size is 8.5.

If I try to reset the font back to match the parent control's 8.5, it then sets it to 3/4 of that, which is 6.375, too small to read. I would have to set it to 4/3 * 8.5 to get it to match the WinForms font size.

I call the sample code above with 10.0, and then copy the text into wordpad, and it says I have 7.5 point font. And so forth.

I don't have any UI scaling going on. Windows screen resolution is set at 100%. I overrode the ScaleCore in the ElementHost parent control and put a breakpoint, and it shows that the scaling is set at 1:1.

Why is it scaling everything 3/4? Is that a universal constant that I should just multiply and divide by whenever I read/write the font size from this control?

Upvotes: 0

Views: 571

Answers (1)

Colin Smith
Colin Smith

Reputation: 12550

The FontSize you specify should be in DIPs (device-independent pixels).

When the RichTextBox is given a size it calculates/maps it back to the nearest point size to use.

Thus you need to do a calculation that will calculate a DIP value, which will end up giving you your desired "PointSize" in the RichTextBox.

double sizeindips = (double) new FontSizeConverter().ConvertFrom("8.5pt");

This is effectively what is called underneath by a "converter" when a size is specified with the "pt" suffix in XAML.

Upvotes: 1

Related Questions