Reputation: 115
I'm currently writing a maui app in .NET 8.0 and after a method is complete, I usually display a message announcing the procedure was completed successfully, and I do this using the DisplayAlert()
command.
However, what I am looking for on certain procedures is for the DisplayAlert()
to close automatically after a few seconds if the OK button is not clicked.
Is there a way to do this?
If it cannot be done with DisplayAlert()
is there another message box or class that is capable of this function?
Upvotes: 1
Views: 119
Reputation: 224
Here is my solution.
------ Update ------
Here I use the community code.
private async void OnCounterClicked(object sender, EventArgs e)
{
popup = new CommunityToolkit.Maui.Views.Popup
{
Content = new VerticalStackLayout
{
BackgroundColor = Colors.Red,
Children =
{
new Label
{
Text = "This is a very important message!"
,
BackgroundColor = Colors.Red,
},
new Microsoft.Maui.Controls.Grid{
ColumnDefinitions ={
new Microsoft.Maui.Controls.ColumnDefinition {
Width=GridLength.Auto
},
new Microsoft.Maui.Controls.ColumnDefinition {
Width=GridLength.Auto
}
},
Children = {
new Microsoft.Maui.Controls.Button{
Text = "Cancel"
},
}
}
}
}
};
this.ShowPopup(popup);
await DelayTask();
}
public async Task DelayTask() {
await Task.Delay(3000);
popup.Close();
}
Upvotes: 2
Reputation: 25991
Here's a reusable DisplayPopup
that takes arguments similar to DisplayAlert. The VerticalStackLayout is initially set to be invisible with Opacity = 0.0
, allowing FadeTo to be used for animating the Popup reveal and concealment.
async Task DisplayPopup(string title, string message, string cancel)
{
VerticalStackLayout verticalStackLayout;
CommunityToolkit.Maui.Views.Popup popup = new()
{
Content = verticalStackLayout = new VerticalStackLayout
{
Padding = new Thickness(20),
Opacity = 0.0,
Children =
{
new Label { Text = title, FontSize = 24 },
new Label { Text = message, FontSize = 16 }
}
}
};
verticalStackLayout.Loaded += async (s, e) =>
{
await verticalStackLayout.FadeTo(1.0, 250);
await Task.Delay(1000);
await verticalStackLayout.FadeTo(0.0, 250);
await popup.CloseAsync();
};
await this.ShowPopupAsync(popup);
}
Upvotes: 2