Search code examples
c#wpf-controls.net-4.6.2

In .NET Framework 4.6.2 the FormattedText() is Obsoleted, how can I fix it


When I try to build the WPF project with .net framework 4.6.2, I got an error, Because the FormattedText() is Obsoleted as below: [Obsolete("Use the PixelsPerDip override", false)] public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground);

The new override method is public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground, double pixelsPerDip);

Q: How can I determine the pixelsPerDip ?

Q: How can I use old constructor without pixelsPerDip?, because the pixelsPerDip is useless for my project.


Solution

  • You need to calculate the DPI of your monitor, see: How can I get the DPI in WPF?

    In Addition, with .Net 4.6.2 come new APIs to handle the DPI awareness, so the above methods might be deprecated (e.g. VisualTreeHelper.GetDpi()). See https://blogs.msdn.microsoft.com/dotnet/2016/08/02/announcing-net-framework-4-6-2/ Here is some example code and a Userguide: https://github.com/Microsoft/WPF-Samples/tree/master/PerMonitorDPI

    IMHO this pararameter has been added so that your program can be dragged between monitors with different DPIs and still is scaled correctly.

    From FromattedText declaration: pixelsPerDip:

    The Pixels Per Density Independent Pixel value, which is the equivalent of the scale factor. For example, if the DPI of a screen is 120 (or 1.25 because 120/96 = 1.25) , 1.25 pixel per density independent pixel is drawn. DIP is the unit of measurement used by WPF to be independent of device resolution and DPIs.

    If you just have 1 monitor and therefore don't need any DPI changed event handling, use the following for example in the OnLoaded() event of your Window (or in your constructor):

    var pixelsPerDip =  VisualTreeHelper.GetDpi(this).PixelsPerDip;