Hello,
Welcome to Microsoft Q&A.
About MVVM in UWP, you could refer to the document. There are samples in the document you could view that where the viewmodles are instanced.
You could use Microsoft.Extensions.DependencyInjection NuGet package to do the dependency injection.
Please check the following steps:
1.Create the MVVM architecture in a C# UWP project.
2.Click Tools in menu, select the option NuGet Package Manager > Manage NuGet Package for Solution… > Browse, enter Microsoft.Extensions.DependencyInjection
in search box, install the package for your project.
3.Create Container
object which maintains all of the dependencies that can be resolved anywhere in the application.
//App.xaml.cs
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
Container = ConfigureDependencyInjection();
}
public IServiceProvider Container { get; }
IServiceProvider ConfigureDependencyInjection()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<IMessageService, MessageService>();
return serviceCollection.BuildServiceProvider();
}
4.Create the MessageService
class and the IMessageService
interface.
//Add a new class to create the interface and class
public interface IMessageService
{
string GetMessage();
}
public class MessageService : IMessageService
{
public string GetMessage()
{
return "Hello from Message Service & Dependency Injection";
}
}
5.Register MessageService
to Container
(referring to the code in step 3).
6.Inject MessageService
into your viewmodel class such as MainViewModel
class.
public class MainViewModel
{
protected IMessageService MessageService { get; }
public string Message { get => MessageService.GetMessage(); }
public MainViewModel(IMessageService messageService)
{
MessageService = messageService;
……
}
……
}
7.Resolve the MainViewModel
, and inject the dependencies by using ActivatorUtilities
function to inject parameters into the constructor.
//MainPage.xaml.cs
public MainPage()
{
this.InitializeComponent();
var container = ((App)App.Current).Container;
DataContext = ActivatorUtilities.GetServiceOrCreateInstance(container, typeof(MainViewModel));
}
8.Show the message in page.
//MainPage.xaml
<Grid>
<TextBlock Text="{Binding Message}" Margin="10" FontSize="20"/>
</Grid>
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.