Home > Mobile >  System.Windows.PresentationSource.FromVisual(...) returned null in WPF
System.Windows.PresentationSource.FromVisual(...) returned null in WPF

Time:09-06

I am programming a plugin for AutoCAD using WPF. This is constructor for WPF window dialog. I caught this problem when defining dpiFactor variable:

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?

CodePudding user response:

This is because the Visual is not loaded yet, thus, you can fix it by executing FromVisual() call inside the Loaded event like this

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

CodePudding user response:

You can get the system DPI scale in Window's constructor.

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.

  • Related