Skip to content

[Bug] DataContext null on first launch, works after Hot Reload (ViewMap timing issue) #2985

@carldebilly

Description

@carldebilly

Problem Description

During navigation setup with ViewMap, the DataContext is sometimes null on first application launch, but works correctly after Hot Reload. This suggests a timing race condition during initial Host construction and first navigation.

Environment

  • Uno Platform: 6.4.195
  • Uno.Extensions.Navigation: 7.0.4
  • .NET: 10.0.1
  • Target: net10.0-desktop (Windows)

Reproduction Steps

  1. Create a page with ViewMap registration:
// App.xaml.cs
services.AddTransient<MyViewModel>();
.UseNavigation(new ViewMap<MyPage, MyViewModel>())
  1. Navigate to the page on app startup:
await navigator.NavigateViewModelAsync<MyViewModel>(this);
  1. Check DataContext in Page.Loaded:
public MyPage()
{
    InitializeComponent();
    this.Loaded += (s, e) =>
    {
        Console.WriteLine($"DataContext: {DataContext?.GetType().Name ?? "NULL"}");
    };
}

Expected Behavior

DataContext should be set to the ViewModel instance immediately on first launch.

Actual Behavior

  • First launch: DataContext: NULL (bindings don't work)
  • After Hot Reload (make any XAML change and save): DataContext: MyViewModel (everything works)

The ViewModel constructor is never called on first launch, but is called after Hot Reload.

Diagnosis

Verification shows the ViewModel IS registered in DI and the ViewMap IS registered:

// This diagnostic code shows:
var app = Application.Current as App;
var vm = app.Host?.Services.GetService<MyViewModel>();
Console.WriteLine($"ViewModel in DI: {vm != null}"); // True
Console.WriteLine($"DataContext set: {DataContext != null}"); // False on first launch

This confirms the issue is in the ViewMap → DataContext assignment timing, not in registration.

Current Workaround

Manual DataContext fallback in Page.Loaded (ugly but functional):

private void OnPageLoaded(object sender, RoutedEventArgs e)
{
    if (DataContext == null && Application.Current is App app)
    {
        // Fallback: manually resolve from DI if ViewMap failed
        DataContext = app.Host?.Services.GetService<MyViewModel>();
        Console.WriteLine("[MyPage] Applied DataContext fallback");
    }
}

Impact

  • Breaks MVVM bindings on first application launch
  • Requires manual workarounds
  • Confusing developer experience (works after Hot Reload but not initially)
  • May affect other platforms beyond Windows desktop

Questions

  1. Is this a known issue in the navigation initialization sequence?
  2. Should there be a built-in fallback mechanism or helper?
  3. Is there a recommended pattern to ensure DataContext assignment timing?

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions