CommunityToolkit / MVVM-Samples

Sample repo for MVVM package
Other
1.11k stars 222 forks source link

Usage of view models in XAML Designer in Visual Studio or Blend #22

Open hansmbakker opened 3 years ago

hansmbakker commented 3 years ago

Ask:

It would be great to see a recommended approach for

Rationale:

The XAML Designer does not automatically load C# code. E.g. if you register your viewmodels with dependency injection (which you make available through a property on App and in your codebehind you write this.DataContext = ((App)Application.Current).Services.GetService<MyFancyViewModel>(); then the XAML designer will not be able to load it.

The Blend / the XAML designer can only load objects with a default (parameterless) constructor that are initialized in XAML itself, e.g.

<Page.DataContext>
   <vm:MyViewModel x:Name="ViewModel" />
</Page.DataContext>

One suggested solution to this (which MVVMLight did) was the use of the ViewModelLocator pattern - which you could include in your XAML and which would construct the viewmodel for you.

Some relevant links:

michael-hawker commented 3 years ago

I know UWP doesn't handle DesignTime data the best compared to WPF in general; however, I do know they just improved this scenario in the latest VisualStudio update, so we should at least make sure that scenario can work and provide it as an example, see release notes here: https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes-preview#xaml-tools-wpf-uwp--xamarinforms

hansmbakker commented 3 years ago

Aham, that one was mentioned in the discord chat as well. Unfortunately I can't get it to work (I'm on 16.8 preview 3 but the designer doesn't seem to pick up any of the alternatives. I did not try Binding, only x:Bind).

Thank you for looking into this!

michael-hawker commented 3 years ago

There's also the general issue on WinUI filed here that I commented on: https://github.com/microsoft/microsoft-ui-xaml/issues/1948#issuecomment-583046229

I had even tried porting the WPF DesignTime data sample to UWP for comparison.

michael-hawker commented 3 years ago

@hansmbakker I know the recent 16.8 VS shipped with improvement to the DesignTime Data story, wondering if you've noticed any improvements?