I am currently developing a .NET 8 MAUI targeted only on Windows platform, specifically, Target Windows Framework is 10.0.19041.0.
This .NET 8 MAUI project is contained within a larger .net solution. I am using MVVM pattern, and in the .NET 8 MAUI project I have a ContentView with its ViewModel. Lets call them InfoView (which is the VIEW) and InfoViewModel (ViewModel).
This InfoView(ContentView xaml) is used in multiple places in my UI, meaning is called from other ContentPages and such. The problem is that for each place the InfoView (ContentView) is called from another ContentPage, it creates a new instance of the view model and I only want a SINGULAR instance, because that viewmodel instance is hooked to several events, and if there are multiple instances of the view model, all those events will trigger for each instance which will decrease the app’s performance.
Here is the MauiProgram.cs:
...
builder.Services.AddSingleton<InfoView>();
builder.Services.AddSingleton<InfoViewModel>();
...
Here is the InfoView code behind:
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;
}
...
}
Viewmodel code:
public partial class InfoViewModel : ObservableObject
{
// ... members and properties
public InfoViewModel()
{
// ... other initializations and event hooks
}
}
And here is how I call the InfoView (ContentView page) from other locations in xaml:
<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>
**<local:SequenceInfoView Padding="12, 0"/>**
</Border>
</ContentPage>
I have tried to dependency inject the view model in the code behind but then I have an error stating that the InfoView (ContentView) is missing an empty constructor.
I appreciate any input, thank you!