MVVM-Samples
MVVM-Samples copied to clipboard
Usage of view models in XAML Designer in Visual Studio or Blend
Ask:
It would be great to see a recommended approach for
- how to use the view models in the XAML Designer (in Visual Studio or Blend).
- best practices around switching between real view models/ services and view models containing sample data
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:
- https://docs.microsoft.com/en-us/windows/uwp/data-binding/displaying-data-in-the-designer
- https://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates
- https://stackoverflow.com/questions/29399157/how-do-i-specify-datacontext-viewmodel-type-to-get-design-time-binding-checkin/29399984
- https://stackoverflow.com/questions/25366291/how-to-handle-dependency-injection-in-a-wpf-mvvm-application
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
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!
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.
@hansmbakker I know the recent 16.8 VS shipped with improvement to the DesignTime Data story, wondering if you've noticed any improvements?