{"record":{"id":"1c94ecd079a81a22","repo":"lepoco/wpfui","slug":"dpiscale-is-not-initialized","errorCode":null,"errorMessage":"dpiScale is not initialized.","messagePattern":"dpiScale is not initialized\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Wpf.Ui/Controls/TitleBar/TitleBar.cs","lineNumber":762,"sourceCode":"                return htResult;\n            case PInvoke.WM_NCHITTEST when this.IsMouseOverElement(lParam) && !isMouseOverHeaderContent:\n                handled = true;\n                return (IntPtr)PInvoke.HTCAPTION;\n            default:\n                return IntPtr.Zero;\n        }\n    }\n\n    /// <summary>\n    /// Show 'SystemMenu' on mouse right button up.\n    /// </summary>\n    private void TitleBar_MouseRightButtonUp(object sender, MouseButtonEventArgs e)\n    {\n        Point point = PointToScreen(e.GetPosition(this));\n\n        if (dpiScale is null)\n        {\n            throw new InvalidOperationException(\"dpiScale is not initialized.\");\n        }\n\n        SystemCommands.ShowSystemMenu(\n            _parentWindow as Window,\n            new Point(point.X / dpiScale.Value.DpiScaleX, point.Y / dpiScale.Value.DpiScaleY)\n        );\n    }\n\n    private T GetTemplateChild<T>(string name)\n        where T : DependencyObject\n    {\n        DependencyObject element = GetTemplateChild(name);\n\n        if (element is not T tElement)\n        {\n            throw new InvalidOperationException(\n                $\"Template part '{name}' is not found or is not of type {typeof(T)}\"\n            );","sourceCodeStart":744,"sourceCodeEnd":780,"githubUrl":"https://github.com/lepoco/wpfui/blob/ffebacd61058170cf63864b7d5aa730cffff848a/src/Wpf.Ui/Controls/TitleBar/TitleBar.cs#L744-L780","documentation":"TitleBar caches the screen DPI in the static field dpiScale via 'dpiScale ??= VisualTreeHelper.GetDpi(this)' inside the window's ContentRendered handler. The right-click handler TitleBar_MouseRightButtonUp reads dpiScale to convert pointer coordinates before opening the system menu. If a right-click arrives before ContentRendered has run (dpiScale still null), the handler throws InvalidOperationException.","triggerScenarios":"User right-clicks the title bar during the brief window between the control being interactive and the owning window firing ContentRendered - e.g. on a very slow first render, or programmatically raising MouseRightButtonUp in tests before the window has rendered.","commonSituations":"Automated UI tests that drive mouse input before showing the window fully; very heavy first-frame rendering that delays ContentRendered; custom windows that suppress ContentRendered.","solutions":["Ensure the owning window has rendered (ContentRendered fired) before driving title-bar input in tests.","In production this is a transient race; suppress right-click handling until the window is fully loaded, or initialise dpiScale earlier.","If subclassing TitleBar, set dpiScale via VisualTreeHelper.GetDpi in OnLoaded as an additional init point."],"exampleFix":"// guard before invoking system menu in a subclass\nprotected override void OnMouseRightButtonUp(MouseButtonEventArgs e)\n{\n    if (VisualTreeHelper.GetDpi(this) is { } scale)\n    {\n        base.OnMouseRightButtonUp(e);\n    }\n}","handlingStrategy":"validation","validationCode":"var scale = VisualTreeHelper.GetDpi(titleBar);\nif (scale is { }) { /* safe to compute screen coords */ } else { /* window not rendered yet */ }","typeGuard":"static bool IsDpiKnown(FrameworkElement e) => VisualTreeHelper.GetDpi(e).DpiScaleX > 0;","tryCatchPattern":"try { /* trigger system menu */ }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"dpiScale\"))\n{\n    _logger.LogWarning(ex, \"Right-click before window rendered; ignoring.\");\n}","preventionTips":["In tests, fully render the window before simulating title-bar right-clicks.","Initialise DPI as early as OnLoaded in a TitleBar subclass.","Avoid programmatic input during the pre-ContentRendered window."],"tags":["titlebar","dpi","race-condition","wpf"],"backgroundTag":null,"analyzedSha":"ffebacd61058170cf63864b7d5aa730cffff848a","analyzedAt":"2026-08-13T21:36:01.370Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}