Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Trying to avoid Xaml, how to set AutowireViewModel by code?

WinterCloudWinterCloud GBMember ✭✭✭

Just started working on Prism, and something like AutowireViewModel, how to set it to true by using code instead of Xaml?

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/ xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" prism:ViewModelLocator.AutowireViewModel="True" x:Class="HelloXFPrism.Views.SpeakPage">

Thanks in advance.

Why not using Xaml?
The problems of Xaml in Xamarin are irritating me greatly, so I'm trying to avoid xaml all together.

Best Answer

Answers

  • WinterCloudWinterCloud GBMember ✭✭✭

    @NMackay said:
    Just register the viewmodel/page in the container instead.

     Container.RegisterTypeForNavigation<FavPage,FavPageViewModel>(PageLibrary.PageKeyFav);
    

    It's a little quicker too.

    I won't get into the XAML debate.

    Thanks a lot for that. It seems Prism auto register that view model if follows the naming pattern. Handy, no extra work needed at all.

  • NMackayNMackay GBInsider, University admin
    edited June 2017

    Autowire has it's uses, i generally explicitly use it when I'm lazy loading widgets into a dashboard that have their own viewmodel and are loaded on demand but for the main application pages I use the approach above.

    You can override the naming convention as well if you wish, Prism is a really nice framework.

  • WolfgangSchreursWolfgangSchreurs NLMember ✭✭
    edited July 2019

    From whatever view you're in, in the code you should also be able to do something similar to the following:

    ViewModelLocator.SetAutoWireViewModel(this, true);

    I used that approach with the ViewModelLocator from the eShopOnContainers example and with that ViewModelLocator it works fine. Might be a bit different when using Prism or some other MVVM framework, but the same idea.

Sign In or Register to comment.