Hello,
You can do this by Ioc (Inversion of control)
Firstly, install the CommunityToolkit.Mvvm nugget package.
Then, create an interface for pag.
public interface IPage
{
public Page GetCurrentPage();
}
Next, Configure and resolve services in the App.xaml.cs.
public partial class App : Application
{
public App()
{
InitializeComponent();
Services = ConfigureServices();
MainPage = new AppShell();
}
/// <summary>
/// Gets the current <see cref="App"/> instance in use
/// </summary>
public new static App Current => (App)Application.Current;
public IServiceProvider Services { get; }
/// <summary>
/// Configures the services for the application.
/// </summary>
private static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.AddSingleton<IPage, MainPage>();
return services.BuildServiceProvider();
}
}
Open your MainPage's background. You can implement the IPage
and return this Mainpage in GetCurrentPage
method.
public partial class MainPage : ContentPage, IPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = new MyViewModel();
}
public Page GetCurrentPage()
{
return this;
}
In the end, you can get the MainPage in the Viewmodel.
internal class MyViewModel
{
public ICommand MyCommand { get; set; }
public MyViewModel()
{
MyCommand = new Command((e) =>
{
IPage page = App.Current.Services.GetService<IPage>();
var mainPage= page.GetCurrentPage();
});
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
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.