You will not usually create instances of the Window class directly; instead the Window class is usually sub-classed for each type of window to be shown by an application. For information on how to create new window classes from templates see the quickstart.
The main window is the window passed to ApplicationLifetime.MainWindow in the OnFrameworkInitializationCompleted method of your your App.axaml.cs file:
It can be retrieved at any time by casting Application.ApplicationLifetime IClassicDesktopStyleApplicationLifetime.
Mobile and browser platforms don't have a concept of Window in Avalonia. Instead you need to set MainView control in Application.ApplicationLifetime when it implements ISingleViewApplicationLifetime interface.
Show, hide and close a window
You can show a window using the Show method:
Windows can be closed using the Close method. This has the same effect as when a user clicks the window's close button:
Note that once a window has been closed, it cannot be shown again. If you want to re-show the window then you should use the Hide method:
window.Close();
// A closed window cannot be shown.
window.Show();
window.Hide();
// Window can now be shown again later
window.Show();
// Here we assume this code is executed from our current Window class and "this" object is a Window.
// Alternatively you can get global MainWindow from Application.ApplicationLifetime casted to IClassicDesktopStyleApplicationLifetime.
var ownerWindow = this;
var window = new MyWindow();
window.ShowDialog(ownerWindow);
var window = new MyWindow();
await window.ShowDialog(ownerWindow);
public class MyDialog : Window
{
public MyDialog()
{
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
Close("OK Clicked!");
}
}
var dialog = new MyDialog();
// The result is a string so call `ShowDialog<string>`.
var result = await dialog.ShowDialog<string>(ownerWindow);