在 .NET Framework 4.6.2 中,FormattedText() 已过时,我该如何修复它

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

当我尝试使用 .net Framework 4.6.2 构建 WPF 项目时,出现错误,因为 FormattedText() 已过时,如下所示: [已过时("Use the PixelsPerDip override",假)] public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface 字体, double emSize, Brush foreground);

新的覆盖方法是 public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface 字体, double emSize, Brush foreground, double pixelsPerDip);

问:如何确定 pixelsPerDip?

问:如果没有 pixelsPerDip,我如何使用旧的构造函数?因为 pixelsPerDip 对我的项目没有用。

您需要计算显示器的DPI,参见: How can I get the DPI in WPF?

此外,.Net 4.6.2 提供了新的 API 来处理 DPI 感知,因此上述方法可能会被弃用(例如 VisualTreeHelper.GetDpi())。 参见 https://blogs.msdn.microsoft.com/dotnet/2016/08/02/announcing-net-framework-4-6-2/ 这是一些示例代码和用户指南: https://github.com/Microsoft/WPF-Samples/tree/master/PerMonitorDPI

恕我直言,已添加此参数,以便您的程序可以在具有不同 DPI 的显示器之间拖动,并且仍然可以正确缩放。

来自 FromattedText 声明: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.

如果您只有 1 个监视器,因此不需要任何 DPI 更改事件处理,请在 Window(或构造函数)的 OnLoaded() 事件中使用以下示例:

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

接受的答案并没有错,但要阅读的文本相当多,最后您仍然没有直接的解决方案,您可以快速输入并解决问题。

警告说 FormattedText() 的这一特定重载已被废弃,但存在另一个您应该使用的重载。

所以,一般来说,您需要做的就是替换这个:

new FormattedText( ... );

有了这个:

new FormattedText( ..., 1.0 );