Aller au contenu

Fenêtres et dialogues

Configurer une fenêtre, en ouvrir d'autres, attendre une réponse.

Propriétés de fenêtre

<Window Title="Éditeur"
        Width="1000" Height="650"
        MinWidth="600" MinHeight="400"
        WindowStartupLocation="CenterScreen"
        WindowState="Normal"
        CanResize="True"
        ShowInTaskbar="True"
        Topmost="False"
        Icon="/Assets/app.ico" />
Aperçu · WindowStartupLocation
Fenêtre
CenterScreen : centre de l'écran
PropriétaireDialogue
CenterOwner : centre de la fenêtre parente
Position
Manual : propriété Position
Propriété Valeurs
WindowStartupLocation Manual, CenterScreen, CenterOwner
WindowState Normal, Minimized, Maximized, FullScreen
SizeToContent Manual, Width, Height, WidthAndHeight

v12

WindowState ne peut plus être défini dans un style.

Ouvrir une autre fenêtre

var fenetre = new ParametresWindow();
fenetre.Show(this);    // "this" = propriétaire : reste au-dessus, se ferme avec

Fenêtre modale avec résultat

sequenceDiagram
  participant M as MainWindow
  participant D as RenommerWindow
  M->>D: await ShowDialog(this)
  Note over M: bloquée (modale)
  D->>D: l'utilisateur saisit puis clique OK
  D-->>M: Close("nouveau-nom.txt")
  Note over M: reprend avec le résultat
Aperçu · la fenêtre parente est inaccessible tant que le dialogue est ouvert
Fichiers
ancien-nom.txt
Renommer
private async void OnRenommer(object? sender, RoutedEventArgs e)
{
    var dialogue = new RenommerWindow("ancien-nom.txt");
    string? nouveauNom = await dialogue.ShowDialog<string?>(this);

    if (nouveauNom is not null)
        Fichier.Text = nouveauNom;
}
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="MonApp.RenommerWindow"
        Title="Renommer" SizeToContent="WidthAndHeight"
        CanResize="False" WindowStartupLocation="CenterOwner">
  <StackPanel Margin="20" Spacing="12" Width="320">
    <TextBox x:Name="Nom" />
    <StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
      <Button Content="Annuler" IsCancel="True" Click="OnAnnuler" />
      <Button Content="OK" IsDefault="True" Classes="accent" Click="OnOk" />
    </StackPanel>
  </StackPanel>
</Window>
public partial class RenommerWindow : Window
{
    public RenommerWindow() => InitializeComponent();   // requis par le prévisualiseur

    public RenommerWindow(string nomActuel) : this()
    {
        Nom.Text = nomActuel;
        Opened += (_, _) => { Nom.Focus(); Nom.SelectAll(); };
    }

    private void OnOk(object? s, RoutedEventArgs e) => Close(Nom.Text);
    private void OnAnnuler(object? s, RoutedEventArgs e) => Close(null);
}

Boîte de confirmation réutilisable

public static class Dialogues
{
    public static Task<bool> ConfirmerAsync(Window parent, string titre, string message)
    {
        var dialogue = new Window
        {
            Title = titre,
            SizeToContent = SizeToContent.WidthAndHeight,
            CanResize = false,
            WindowStartupLocation = WindowStartupLocation.CenterOwner
        };

        var oui = new Button { Content = "Oui", IsDefault = true, Classes = { "accent" } };
        var non = new Button { Content = "Non", IsCancel = true };
        oui.Click += (_, _) => dialogue.Close(true);
        non.Click += (_, _) => dialogue.Close(false);

        dialogue.Content = new StackPanel
        {
            Margin = new Thickness(20), Spacing = 16, MaxWidth = 360,
            Children =
            {
                new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
                new StackPanel
                {
                    Orientation = Orientation.Horizontal, Spacing = 8,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    Children = { non, oui }
                }
            }
        };

        return dialogue.ShowDialog<bool>(parent);
    }
}
if (await Dialogues.ConfirmerAsync(this, "Supprimer", "Supprimer ce fichier ?"))
    Supprimer();

Empêcher la fermeture

protected override async void OnClosing(WindowClosingEventArgs e)
{
    base.OnClosing(e);
    if (!_modifie || _fermetureConfirmee) return;

    e.Cancel = true;
    if (await Dialogues.ConfirmerAsync(this, "Quitter", "Quitter sans enregistrer ?"))
    {
        _fermetureConfirmee = true;
        Close();
    }
}

Barre de titre personnalisée

Étend le contenu sous la barre de titre en gardant les boutons système.

Aperçu · normal / ExtendClientAreaToDecorationsHint="True"
Mon application
votre contenu
défaut : barre de titre système
Mon application
votre contenu
étendu : vous dessinez la barre, boutons conservés
<Window ExtendClientAreaToDecorationsHint="True"
        ExtendClientAreaTitleBarHeightHint="40">
  <Grid RowDefinitions="40,*">
    <Border Background="#6D28D9" IsHitTestVisible="False">
      <TextBlock Text="Mon application" Foreground="White"
                 VerticalAlignment="Center" Margin="80,0,0,0" />
    </Border>
    <ContentControl Grid.Row="1" />
  </Grid>
</Window>

Sans décoration du tout v12

<Window WindowDecorations="None" Background="Transparent"
        TransparencyLevelHint="Transparent">
  <Border Background="White" CornerRadius="12" PointerPressed="OnDeplacer">
    <!-- … -->
  </Border>
</Window>
private void OnDeplacer(object? sender, PointerPressedEventArgs e) => BeginMoveDrag(e);

WindowDecorations : Full, BorderOnly, None (remplace SystemDecorations d'Avalonia 11).

Aperçu · les 3 valeurs de WindowDecorations
Titre
Full
BorderOnly : bordure, pas de barre
forme libre
None : rien, à vous de tout dessiner

Effet de transparence (Mica, Acrylic)

<Window TransparencyLevelHint="Mica, AcrylicBlur, Blur"
        Background="Transparent">
  <Panel>
    <ExperimentalAcrylicBorder IsHitTestVisible="False">
      <ExperimentalAcrylicBorder.Material>
        <ExperimentalAcrylicMaterial TintColor="Black" TintOpacity="1" MaterialOpacity="0.6" />
      </ExperimentalAcrylicBorder.Material>
    </ExperimentalAcrylicBorder>
    <!-- contenu -->
  </Panel>
</Window>

Mémoriser position et taille

protected override void OnClosing(WindowClosingEventArgs e)
{
    base.OnClosing(e);
    Reglages.Position = Position;          // PixelPoint
    Reglages.Taille = ClientSize;          // Size
    Reglages.Maximisee = WindowState == WindowState.Maximized;
}

Plusieurs écrans

foreach (var ecran in Screens.All)
    Debug.WriteLine($"{ecran.Bounds} · échelle {ecran.Scaling} · principal {ecran.IsPrimary}");