Skip to content

Commit 08b3e0e

Browse files
committed
fix: Ensure app is started after native WPF template is applied
If the initial page of the application has an input field as the first focusable element, an exception would occur, as the native overlay layer was not initialized yet. Moving app startup after WPF's OnApplyTemplate ensures that this condition does not occur.
1 parent 37323c2 commit 08b3e0e

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

src/Uno.UI.Runtime.Skia.Wpf/WpfHost.cs

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@ public class WpfHost : WpfControl, WinUI.ISkiaHost
4646
private const string NativeOverlayLayerPart = "NativeOverlayLayer";
4747

4848
private readonly bool designMode;
49-
49+
private readonly Func<UnoApplication> _appBuilder;
50+
51+
private bool _appStarted = false;
52+
5053
[ThreadStatic] private static WpfHost _current;
5154

5255
private WpfCanvas? _nativeOverlayLayer = null;
@@ -99,20 +102,13 @@ public WpfHost(global::System.Windows.Threading.Dispatcher dispatcher, Func<WinU
99102
public WpfHost(global::System.Windows.Threading.Dispatcher dispatcher, Func<WinUI.Application> appBuilder)
100103
{
101104
_current = this;
105+
_appBuilder = appBuilder;
102106

103107
designMode = DesignerProperties.GetIsInDesignMode(this);
104108

105-
void CreateApp(WinUI.ApplicationInitializationCallbackParams _)
106-
{
107-
var app = appBuilder();
108-
app.Host = this;
109-
}
110-
111109
Windows.UI.Core.CoreDispatcher.DispatchOverride = d => dispatcher.BeginInvoke(d);
112110
Windows.UI.Core.CoreDispatcher.HasThreadAccessOverride = dispatcher.CheckAccess;
113111

114-
WinUI.Application.StartWithArguments(CreateApp);
115-
116112
WinUI.Window.InvalidateRender += () =>
117113
{
118114
InvalidateOverlays();
@@ -156,6 +152,26 @@ public override void OnApplyTemplate()
156152
base.OnApplyTemplate();
157153

158154
_nativeOverlayLayer = GetTemplateChild(NativeOverlayLayerPart) as WpfCanvas;
155+
156+
// App needs to be created after the native overlay layer is properly initialized
157+
// otherwise the initially focused input element would cause exception.
158+
StartApp();
159+
}
160+
161+
private void StartApp()
162+
{
163+
if (_appStarted)
164+
{
165+
return;
166+
}
167+
168+
void CreateApp(WinUI.ApplicationInitializationCallbackParams _)
169+
{
170+
var app = _appBuilder();
171+
app.Host = this;
172+
}
173+
174+
WinUI.Application.StartWithArguments(CreateApp);
159175
}
160176

161177
private void MainWindow_StateChanged(object? sender, EventArgs e)

0 commit comments

Comments
 (0)