Skip to content

[Documentation] [Navigation] ViewMap/DataContext Troubleshooting and Internal Mechanism Documentation #2983

Open

Description

@carldebilly

Problem Statement

I recently spent significant time debugging what seemed like a simple issue: a button in my XAML wasn't responding to clicks. The bindings appeared correct, the UI rendered fine, but nothing worked. The root cause was that DataContext was null, and the current documentation doesn't adequately explain:

  1. How ViewMap actually works internally
  2. When and how DataContext gets assigned
  3. How to troubleshoot when it doesn't work
  4. What the prerequisites are (DI + ViewMap relationship)

The current documentation leaves developers without clear guidance on these critical aspects of the navigation system.


My Debugging Journey

Here's what I had to figure out to solve this issue:

Attempt 1: Visual Debugging

Added a debug TextBlock to display the DataContext type:

<TextBlock x:Name="DebugText" Foreground="Red" FontSize="20"/>
this.Loaded += (s, e) => {
    DebugText.Text = $"DataContext: {DataContext?.GetType().Name ?? "NULL"}";
};

Result: Confirmed DataContext was NULL. But why?

Attempt 2: Constructor Logging

public MyPage()
{
    Debug.WriteLine("[MyPage] Constructor called");
    InitializeComponent();
    Debug.WriteLine($"[MyPage] DataContext: {DataContext?.GetType().Name ?? "NULL"}");
}

Problem discovered: Debug.WriteLine() doesn't appear in PowerShell background jobs. Had to switch to Console.WriteLine().

Result: Page constructor runs, but DataContext is NULL after InitializeComponent().

Attempt 3: ViewModel Constructor Logging

public class MyViewModel : ObservableObject
{
    public MyViewModel(INavigator navigator)
    {
        Console.WriteLine("[MyViewModel] Constructor called");
    }
}

Result: No log output on first launch. ViewModel was never created!

Attempt 4: Verify DI Registration

Checked App.xaml.cs:

services.AddTransient<MyViewModel>(); // ✓ Present
.UseNavigation(new ViewMap<MyPage, MyViewModel>()) // ✓ Present

Everything looked correct, but still didn't work.

Attempt 5: Hot Reload Test

Made a minor XAML change and saved the file.

BREAKTHROUGH: After Hot Reload:

[MyViewModel] Constructor called
[MyPage] Loaded - DataContext: MyViewModel

Conclusion: ViewMap WORKS, but only after Hot Reload. There's an initialization timing issue on first app launch.


What's Missing from the Documentation

The current View and ViewModel page doesn't adequately cover:

1. How ViewMap Actually Works (Critical Gap)

Current state: Documentation says ViewMap "associates" a View with a ViewModel, but doesn't explain the mechanism.

What's needed: A clear explanation like:

When you register new ViewMap<MyPage, MyViewModel>() and navigate to MyViewModel, the framework:

  1. Resolves MyViewModel from the DI container
  2. Creates a new instance of MyPage
  3. Automatically sets myPageInstance.DataContext = myViewModelInstance

Important: You do NOT need to manually set DataContext in your page's code-behind. ViewMap handles this automatically.

Why it matters: Without this clarity, developers may assume they need to manually wire up DataContext, leading to incorrect implementations and confusion.


2. Troubleshooting Section (Critical Gap)

Current state: No troubleshooting guidance exists.

What's needed: A dedicated troubleshooting page covering:

Problem: DataContext is null, bindings don't work

Diagnostic Steps:

  1. Verify DataContext in Page.Loaded:

    this.Loaded += (s, e) => {
        Console.WriteLine($"DataContext: {DataContext?.GetType().Name ?? "NULL"}");
    };
  2. Check BOTH registrations are present:

    // Both required:
    services.AddTransient<MyViewModel>();  // DI registration
    .UseNavigation(new ViewMap<MyPage, MyViewModel>())  // ViewMap registration
  3. Verify ViewModel constructor is called:

    public MyViewModel(INavigator navigator) {
        Console.WriteLine($"[MyViewModel] Created");
    }

    If this log doesn't appear → DI registration issue or missing dependency.

  4. Test with Hot Reload:

    • Make a small XAML change
    • If DataContext works after Hot Reload but not on first launch → Initialization timing issue

Why it matters: Without this guidance, developers are left without a clear path to diagnose and resolve issues.


3. DI + ViewMap Prerequisites (Critical Gap)

Current state: Documentation doesn't clearly state that BOTH registrations are required.

What's needed: A clear "Prerequisites" section:

For ViewMap to work, you must complete BOTH steps:

Step 1: Register ViewModel in DI:

services.AddTransient<MyViewModel>();

Step 2: Register ViewMap:

.UseNavigation(new ViewMap<MyPage, MyViewModel>())

❌ Common Mistakes:

  • Registering only the ViewMap (forgetting DI) → ViewModel can't be resolved
  • Registering only in DI (forgetting ViewMap) → No Page/ViewModel association
  • Using AddSingleton instead of AddTransient → Lifetime issues

Rule: For every ViewMap<TPage, TViewModel>, you must have services.AddTransient<TViewModel>().

Why it matters: The dependency between these two registrations isn't obvious from the current documentation.


4. Page/ViewModel Lifecycle Documentation (Important)

Current state: No explanation of when things are created and in what order.

What's needed: A lifecycle diagram:

Navigation Request
    ↓
1. Resolve MyViewModel from DI container → ViewModel constructor called
    ↓
2. Create MyPage instance → Page constructor called
    ↓
3. Set DataContext → myPage.DataContext = myViewModel
    ↓
4. Add to visual tree → Page.Loaded event fires

With implications:

// ❌ RISKY - DataContext might still be null
public MyPage() {
    InitializeComponent();
    var vm = DataContext as MyViewModel; // May be null here!
}

// ✅ SAFE - DataContext is guaranteed
public MyPage() {
    InitializeComponent();
    this.Loaded += (s, e) => {
        var vm = DataContext as MyViewModel; // Always set here
    };
}

Why it matters: Understanding timing prevents bugs and helps developers make informed decisions about where to place initialization code.


5. Debugging Techniques (Important)

Current state: No debugging guidance.

What's needed:

Console Logging vs Debug Logging:

// ❌ NOT visible in PowerShell background jobs
Debug.WriteLine("[MyPage] Constructor");

// ✅ VISIBLE in terminal
Console.WriteLine("[MyPage] Constructor");

Verify ViewModel in DI Container:

var app = Application.Current as App;
var vm = app.Host.Services.GetService<MyViewModel>();
Console.WriteLine($"ViewModel in DI: {vm != null}");
Console.WriteLine($"DataContext set: {DataContext != null}");

Why it matters: These techniques provide developers with concrete tools to diagnose issues quickly.


6. Known Issues Section (Nice to Have)

Current state: No known issues documented.

What's needed: Document the first-launch timing issue:

Known Issue: DataContext may be null on first application launch, but works after Hot Reload.

Workaround:

private void OnPageLoaded(object sender, RoutedEventArgs e)
{
    if (DataContext == null && Application.Current is App app)
    {
        DataContext = app.Host?.Services.GetService<MyViewModel>();
    }
}

Why it matters: Helps developers know they're encountering a known issue and provides a workaround.


Proposed Documentation Structure

The following additions would significantly improve the Uno.Extensions.Navigation documentation:

1. Enhance "View and ViewModel" page:

  • Add "How ViewMap Works Internally" section at the top
  • Add "Prerequisites" section (DI + ViewMap requirements)
  • Add "Page/ViewModel Lifecycle" section

2. Create new "Troubleshooting" page:

  • "DataContext is null" problem with diagnostic steps
  • "ViewModel constructor never called" problem
  • "Multiple ViewModel instances created" explanation
  • Debugging techniques section

3. Create new "Known Issues" page:

  • Document first-launch timing issue
  • Document other common pitfalls

Impact Analysis

This documentation gap likely affects many developers new to Uno.Extensions.Navigation. Improving the documentation would:

  • Reduce time spent debugging common issues
  • Improve developer experience and onboarding
  • Reduce support burden on the team
  • Make the relationship between DI and ViewMap more explicit
  • Provide clear troubleshooting pathways

Environment

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

Activity

  1. changed the title [-][Documentation] ViewMap/DataContext Troubleshooting and Internal Mechanism Documentation[/-] [+][Documentation] [Navigation] ViewMap/DataContext Troubleshooting and Internal Mechanism Documentation[/+] on Dec 18, 2025
  2. DevTKSS commented on Dec 23, 2025

    @DevTKSS
    Contributor

    @carldebilly Would you please include MVUX specifics in these future to be added docs for Navigation?
    there are many problems that we as Users need to workaround and the MCP knowledge lets the agent 90% of the time in my App fallback to mvvm because of this.
    some instructions I allways have to make on-and-on:

    known issues and limitations? Oh there are lots of them!

    And what about when we use to do CustomDialogs? The src/Samples/Playground/* is for me one of the best lookup for not documented Navigation Setup 👀 Could you fed them to the MCP too maybe?
    No VM/Model or Register Routes code here:
    https://platform.uno/docs/articles/external/uno.extensions/doc/Learn/Navigation/Walkthrough/ShowDialog.html
    https://platform.uno/docs/articles/features/dialogs.html?tabs=mvux%2Cxaml outdated, still naming "BindableModel" and doesnt show Registration for Regular custom Contentdialog only if you are using the Actions from Messagedialog. Customization is Difficult. Can only be used if you wish to Dirty your Layer Seperation...
    https://platform.uno/docs/articles/features/dialogs.html?tabs=mvux%2Cxaml#opening-a-contentdialog-from-a-modelviewmodel the headline here is misleading. if a newbe uses this as-is he will fail for the IXamlRootProvider does not exist, but is mentioned there. If you mention such service, we should either have an implementation for this, an interface we can match on (this is also not existing) or even a Codesample that shows us how we can and should do this.
    But better would potentially be to get a IDispatcher and use this to get on the UI thread.

    🤷 just saying...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions