How to do a simple ViewModel first approach in UWP

Mar*_*man 5 c# wpf mvvm uwp

I haven't really found my answer to my problem anywhere, so I really hope that someone actually was solving similar problem before me.

I'm developing an UWP application after I was messing with MVVM stuff in WPF for like a year (no widespread frameworks/libraries, just very basic stuff to get the grasp of it). I've come to the realization that I can't really recreate my beloved patterns in UWP, because it has tighter rules than WPF.

What I did in WPF: What I had was few VMs with INPC and properties, etc. and Views with bindings, usual stuff. It was coupled together by the magic of DataTemplate and a really simple method:

    public static void Show(this ViewModelBase vm)
    {
        CreateWindow(vm).Show();
    }

    private static Window CreateWindow(ViewModelBase vm)
    {
        return new Window
               {
                   Icon = Resources.app_icon.ToImageSource(),
                   Width = 500d,
                   Height = 320d,
                   Content = vm,
                   Title = vm.ToString()
               };
    }
Run Code Online (Sandbox Code Playgroud)

In my ResourceDictionary, I defined all templates for my ViewModel classes, like so:

<DataTemplate DataType="{x:Type local:RandomViewModel}">
    <local:RandomView />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

UWP situation: I started with a ViewModels that derived from ContentControl, which worked as a prototype, but was ugly and severely broke MVVM "rules" (imho). I switched to the DataTemplate ResourceDictionary with underlying static class that I saw on Build (2016?) conference, which led me to my current state. DataTemplate now has to have a x:Key, which prevents me to leave everything so loosely coupled. Of course the DataTemplate works if I explicitly use the key for ContentTemplate, but that's something I wanted to avoid.

After few weeks of thinking and contemplating and being all frustrated with it, I finally decided to ask someone to at least give me a hint of how to deal with this. For this specific application, I don't really want to go down the road of "do-everything" framework. I also wanted to use compiled binding, so the whole Content/DataContext business is gone also.

Is there a elegant (and simple) or obvious solution that I've missed? I'd be really thankful for any useful tips.

Edit: I know that the question is very vague, If I knew exactly what to ask for, I'd probably keep searching the internet / trying to figure things out by myself. I hope you don't mind.

小智 0

你被迫使用 UWP 吗?如果没有,我真的建议使用 MAUI。在那里您可以轻松使用 MVVM 方法。它有什么好处呢?构建 MAUI 应用程序后,您可以轻松地将其部署到 Android、Linux、IOS 和 Windows。尽管 MAUI 的生态系统仍然很薄弱,但我确信这是微软技术堆栈上任何非 Web 应用程序的出路。而且我个人比ie Flutter更喜欢它。