My Goal is to NOT create dependencies between ViewModels.
I have .NET 7 MAUI project.
The situation is simple.
我有MainPage
,并且我使用DI将ViewModel MainPageViewModel
链接到它
services.AddSingleton<MainPageViewModel>();
services.AddSingleton<MainPage>(provider =>
{
return new MainPage()
{
BindingContext = provider.GetRequiredService<MainPageViewModel>(),
};
});
它工作正常,创建了ViewModel,并将其分配给MainPage
个AS中的BindingContext
个,太棒了.
现在,当我像这样将另一个 children 视图放入MainPage
内时
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyNamespace"
x:Class="MyNamespace.MainPage">
<MyNamespace:ChildView />
</ContentPage>
我将它注册到它的ViewModel中,如下所示
services.AddSingleton<ChildViewModel>();
services.AddSingleton<ChildView>(provider =>
{
return new ChildView()
{
BindingContext = provider.GetRequiredService<ChildViewModel>(),
};
});
The MainPage
create the ChildView
directly (by calling its parameterless constructor) without consulting the DI Container
This is causing the lack of Binding for the ViewModel.
- 我不想在
MainPageViewModel
内创建ChildViewModel
并传递它. - 在Prism中,这个问题可以使用区域解决,但目前Prism不支持毛伊语
-
MainPage
的创造是这样的
<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="Trex.Mobile.App.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyNamespace"
Shell.FlyoutBehavior="Disabled">
<ShellContent
Title="Home"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />
</Shell>
and by using this way, the DI container is used.
Can I use something like that for my ChildView
or should I change something fundamentally