Hello,
You can create single instance viewmodel for MyExamplePopUpViewModel
. And I return the popup object to the ClosePopUp
method and close popup window by popup.Close();
method directly.
public partial class MyExamplePopUpViewModel: ObservableObject
{
public static MyExamplePopUpViewModel Instanse { get; } = new MyExamplePopUpViewModel();
private MyExamplePopUpViewModel()
{
}
[ObservableProperty]
public object obj;
public bool shouldClose { get; set; }
[RelayCommand]
void ClosePopUp(object result)
{
Obj = result;
Popup popup = result as Popup;
popup.Close();
shouldClose = true;
}
}
When you need to use this MyExamplePopUpViewModel, just execute MyExamplePopUpViewModel.Instanse;
, no need to new a MyExamplePopUpViewModel object.
Here is my edited MainViewModel.cs
.
public partial class MainViewModel
{
public MainViewModel()
{
}
[RelayCommand]
async Task GoToNext()
{
Shell.Current.ShowPopup(new MyExamplePopUp());
// Close the popup if the flag is set.
if (MyExamplePopUpViewModel.Instanse.shouldClose)
{
// Retrieve and handle the result as an object.
var result = MyExamplePopUpViewModel.Instanse.Obj;
// Handle the result as needed.
// Reset the flag for the next use.
MyExamplePopUpViewModel.Instanse.shouldClose = false;
}
}
}
In the end, I edited the MyExamplePopUp
as well.
In the MyExamplePopUp
layout, I send the popup window to the viewmodel by CommandParameter="{x:Reference this}"
. As note: I added x:Name="this"
in the toolkit:Popup
tag.
<?xml version="1.0" encoding="utf-8" ?>
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiMAKERunning.MyExamplePopUp"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Name="this"
>
<Border>
<VerticalStackLayout>
<Entry Placeholder="name" />
<Entry Placeholder="Age" />
<Entry Placeholder="LastName" />
<Button Text="Back" Command="{Binding ClosePopUpCommand}" CommandParameter="{x:Reference this}"/>
</VerticalStackLayout>
</Border>
</toolkit:Popup>
In the layout background code, I bind this viewmodel by MyExamplePopUpViewModel.Instanse;
, No need to use transferred viewmodel.
public partial class MyExamplePopUp : Popup
{
public MyExamplePopUp()
{
InitializeComponent();
BindingContext = MyExamplePopUpViewModel.Instanse;
}
}
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.