Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 6 Creating Our Own Layout

return (IWidgetViewModel)serviceProvider.GetRequiredSer vice(widgetViewModelType);

}

return null;

}

Breaking this down,

•\

You check whether the supplied displayname has been

 

registered with the factory.

•\

If it has, you use the IServiceProvider to get an

 

instance of the associated widget view model.

Registering the Factory with MauiAppBuilder

Inside your MauiProgram.cs file, you need to register your WidgetFactory with the MauiAppBuilder to make sure any dependencies can resolve it. Open that file and add the following line into the CreateMauiApp method:

builder.Services.AddSingleton<WidgetFactory>();

Registering Your ClockWidget with the Factory

Now that you have your WidgetFactory, you need to modify it so that the factory can create the widget for you. This requires a number of steps, so let’s walk through it.

First, open the ClockWidgetView.xaml.cs file and change it to the following:

using WidgetBoard.ViewModels;

namespace WidgetBoard.Views;

public partial class ClockWidgetView : Label, IWidgetView

{

191

Chapter 6 Creating Our Own Layout

public ClockWidgetView(ClockWidgetViewModel clockWidgetViewModel)

{

InitializeComponent();

WidgetViewModel = clockWidgetViewModel; BindingContext = clockWidgetViewModel;

}

public IWidgetViewModel WidgetViewModel { get; set; }

}

This results in your ClockWidgetView taking a dependency on

ClockWidgetViewModel.

Next, you need to register your widget with the factory. Open your MauiProgram.cs file and add the following lines to the

CreateMauiApp method:

WidgetFactory.RegisterWidget<ClockWidgetView, ClockWidgetView

Model>("Clock");

builder.Services.AddTransient<ClockWidgetView>();

builder.Services.AddTransient<ClockWidgetViewModel>();

This will enable the WidgetFactory to return the clock widget as an option when presented in your overlay.

192