Search code examples
c#wpfautocad

System.Windows.PresentationSource.FromVisual(...) returned null in WPF


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?


Solution

  • 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);
    };