简体   繁体   English

System.Windows.PresentationSource.FromVisual(...) 在 WPF 中返回 null

[英]System.Windows.PresentationSource.FromVisual(...) returned null in WPF

I am programming a plugin for AutoCAD using WPF.我正在使用 WPF 为 AutoCAD 编写插件。 This is constructor for WPF window dialog.这是 WPF window 对话框的构造函数。 I caught this problem when defining dpiFactor variable:我在定义 dpiFactor 变量时发现了这个问题:

public TentCreationDialog(Commands cmd)
        {
            InitializeComponent();

            ...

            exControl = new ExControl(this.textBoxAwingWidth, "AwingCreation");

            ...

            double dpiFactor = System.Windows.PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;
            UserInterfaceCustomScale(dpiFactor);
        }

Does anybody know what could cause this?有人知道是什么原因造成的吗?

This is because the Visual is not loaded yet, thus, you can fix it by executing FromVisual() call inside the Loaded event like this这是因为 Visual 尚未加载,因此,您可以通过像这样在Loaded事件中执行FromVisual()调用来修复它

Loaded += (sender, args) => {
   double dpiFactor = System.Windows.PresentationSource.FromVisual(this)?.CompositionTarget.TransformToDevice.M11 ?? 0;
   UserInterfaceCustomScale(dpiFactor);
};

You can get the system DPI scale in Window's constructor.您可以在 Window 的构造函数中获取系统 DPI 比例。

public MainWindow()
{
    InitializeComponent();
    double dpiScale = VisualTreeHelper.GetDpi(this).PixelsPerDip;
}

However, please note it does not necessarily match actual DPI scale of Window under Per-Monitor DPI environment.但请注意,它不一定与 Per-Monitor DPI 环境下 Window 的实际 DPI 比例相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PresentationSource.FromVisual(this)在WPF中返回null值 - PresentationSource.FromVisual(this) returns null value in WPF Mapsui错误:如何修复PresentationSource为空? - Mapsui Error: How to fix PresentationSource is null? 如何修复此错误(System.Windows.Forms.DataGridViewCell.Value.get 返回 null。) - How Can Fixed This Erorr (System.Windows.Forms.DataGridViewCell.Value.get returned null. ) WPF ComboBox as System.Windows.Media.Colors - WPF ComboBox as System.Windows.Media.Colors NullReferenceException与System.Windows.Controls.WebBrowser WPF - NullReferenceException with System.Windows.Controls.WebBrowser WPF WPF Datagrid [System.Windows.Data错误:4] - WPF Datagrid [System.Windows.Data Error: 4] System.Collections.Specialized.NameValueCollection.this [string] .get返回null - System.Collections.Specialized.NameValueCollection.this[string].get returned null System.Configuration.ConnectionStringSettingsCollection.this[string].get 使用单元测试返回 null - System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null with Unit tests WPF:将字符串转换为 System.Windows.Visibility - WPF: Convert string to System.Windows.Visibility WPF - 从System.Windows.Application继承 - WPF - inherit from System.Windows.Application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM