[英]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.