Search code examples
c#winui-3winui

Why is my Page.DataContext class not found?


im very new to c# and play around something. Now i want to use Models for my Data Handling so but my class is not found. Do you have any suggestion to get it to run?

Fehler XLS0414 Typ 'vm:MyAppViewModel' wurde nicht gefunden. Stellen Sie sicher, dass keine Assemblyreferenz fehlt, und dass alle referenzierten Assemblys erstellt wurden. C:\Users\User\source\repos\MyApp\MyApp\Views\MyApp.xaml 17

MyPage.xaml

xmlns:vm="using:MyApp.ViewModels"

<Page.DataContext>
    <vm:MyAppViewModel />
</Page.DataContext>

MyPage.xaml.cs

public sealed partial class MyPage : Page
{

    public MyPage() => InitializeComponent();

    public MyAppViewModel DataContext
    {
        get =>
            (MyAppViewModel)(
            base.DataContext ?? throw new InvalidOperationException("DataContext is not set.")
        );
        set => base.DataContext = value;
    }
}

Where is the error in my namespaces and/or declarations?

/ViewModels

namespace MyApp.ViewModels;

public partial class MyAppViewModel : ObservableRecipient

Solution

  • After a long search, I have now found the solution. Firstly, it would have been good for you if the app had been created with the Template Studio and additionally used the CommunityToolkit.Mvvm package. Therefore, I had to take the following steps to address the ViewModel.

    App.xaml.cs

    InitializeComponent();
    
    Host = Microsoft.Extensions.Hosting.Host.
    CreateDefaultBuilder().
    UseContentRoot(AppContext.BaseDirectory).
    ConfigureServices((context, services) =>
    {
        // View and ViewModel added
        services.AddTransient<DownloadViewModel>();
        services.AddTransient<DownloadPage>();
    }
    

    Services/PageService.cs

    public PageService()
    {
        //Model and Page added
        Configure<DownloadViewModel, DownloadPage>();
        
    }
    

    Now the DownloadPage.xaml.cs

    public sealed partial class DownloadPage : Page
    {
        public DownloadViewModel ViewModel
        {
            get;
        }
    
        public DownloadPage()
        {
            ViewModel = App.GetService<DownloadViewModel>();
            InitializeComponent();
        }
    }
    

    After these steps, the model is available in my View and Bindings works perfect.

    If you have the same problem where bindings don't work or the model isn't found, check if the model is correctly registered and the namespaces are correct.

    The example refers to a standard app that was created and preconfigured with Template Studio.

    Template Studio: https://marketplace.visualstudio.com/items?itemName=WASTeamAccount.WindowsTemplateStudio

    MVVM Toolkit: https://learn.microsoft.com/de-de/dotnet/communitytoolkit/mvvm/