MAUI MVVM ContentView 在项目中的多个位置使用,具有多个视图模型,而不是只有一个

问题描述 投票:0回答:1

我目前正在开发一个仅针对Windows平台的.NET 8 MAUI,具体来说,目标Windows框架是10.0.19041.0。

此 .NET 8 MAUI 项目包含在更大的 .net 解决方案中。我正在使用 MVVM 模式,在 .NET 8 MAUI 项目中,我有一个 ContentView 及其 ViewModel。我们称它们为 InfoView(即 VIEW)和 InfoViewModel(ViewModel)。

此 InfoView(ContentView xaml) 在我的 UI 中的多个位置使用,这意味着从其他 ContentPages 等调用。问题是,对于从另一个 ContentPage 调用 InfoView (ContentView) 的每个地方,它都会创建视图模型的新实例,而我只想要一个单一实例,因为该视图模型实例挂接到多个事件,并且如果有多个事件视图模型的实例,所有这些事件都会为每个实例触发,这将降低应用程序的性能。

这是MauiProgram.cs

...
builder.Services.AddSingleton<InfoView>();

builder.Services.AddSingleton<InfoViewModel>();
...

这是背后的InfoView代码

public partial class InfoView: ContentView
{
    private InfoViewModel viewModel;

    public InfoView()
    {
        InitializeComponent();
        // This could not be the best way to do this but here it is
        viewModel = (SequenceInfoViewModel)BindingContext;
    }

    ...
}

查看模型代码:

public partial class InfoViewModel : ObservableObject
{
    // ... members and properties
    public InfoViewModel()
    {
        // ... other initializations and event hooks
    }


}

这是我如何从 xaml 中的其他位置调用 InfoView(ContentView 页面)

<ContentPage ...>
    <Border Grid.Row="1"
            StrokeShape="RoundRectangle 10,10,10,10"
            Margin="4,4,2,2"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="Fill">
        <Border.Background>
            <RadialGradientBrush Center="1.3, 0.7">
                <GradientStop Color="{Binding FlashingStatusColor}"
                              Offset="0.1" />
                <GradientStop Color="DimGray"
                              Offset="1" />
            </RadialGradientBrush>
        </Border.Background>
        <!--> Here is where I use the existing content view<-->
        <local:InfoView Padding="12, 0"/>
    </Border>
</ContentPage>

我尝试在后面的代码中依赖注入视图模型,但随后出现错误,指出 InfoView (ContentView) 缺少空构造函数。

感谢您的任何意见,谢谢!

c# .net mvvm maui
1个回答
0
投票

如果我正确理解你的问题,问题是你正在构建依赖注入,但你实际上并没有注入你的视图模型类。 像下面这样的东西应该可以解决它。

public partial class InfoView: ContentView
{
    private InfoViewModel _viewModel;

    public InfoView(InfoViewModel viewModel)
    {
        _viewModel = viewModel;
        BindingContext = _viewModel;
        InitializeComponent();
    }

    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.