Contrôles personnalisés¶
Trois niveaux : assembler (UserControl), rendre stylable (TemplatedControl), dessiner (Control + Render).
| Besoin | Classe de base |
|---|---|
| Regrouper des contrôles existants, propre à l'appli | UserControl |
| Contrôle réutilisable, dont l'apparence se change par thème | TemplatedControl |
| Rendu entièrement dessiné | Control (voir Dessin) |
flowchart LR
Q{"Que voulez-vous ?"} -->|"assembler des contrôles<br/>existants"| U["UserControl<br/>XAML + code-behind"]
Q -->|"un contrôle réutilisable<br/>dont on change l'apparence"| T["TemplatedControl<br/>code + ControlTheme séparés"]
Q -->|"dessiner pixel par pixel"| C["Control + Render()"]
UserControl¶
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MonApp.Controls.CarteContact"
x:Name="Racine">
<Border Background="White" CornerRadius="12" Padding="12" BoxShadow="0 2 8 0 #14000000">
<StackPanel Spacing="2">
<TextBlock Text="{Binding #Racine.Nom}" FontWeight="Bold" />
<TextBlock Text="{Binding #Racine.Email}" Opacity="0.6" />
</StackPanel>
</Border>
</UserControl>
using Avalonia;
using Avalonia.Controls;
namespace MonApp.Controls;
public partial class CarteContact : UserControl
{
public static readonly StyledProperty<string?> NomProperty =
AvaloniaProperty.Register<CarteContact, string?>(nameof(Nom));
public static readonly StyledProperty<string?> EmailProperty =
AvaloniaProperty.Register<CarteContact, string?>(nameof(Email));
public string? Nom
{
get => GetValue(NomProperty);
set => SetValue(NomProperty, value);
}
public string? Email
{
get => GetValue(EmailProperty);
set => SetValue(EmailProperty, value);
}
public CarteContact() => InitializeComponent();
}
Ada Lovelace
ada@exemple.fr
ada@exemple.fr
Alan Turing
alan@exemple.fr
alan@exemple.fr
flowchart LR
X["XAML parent<br/>Nom='Ada Lovelace'"] --> P["NomProperty<br/>(StyledProperty)"]
B["Binding / Style / Animation"] --> P
P --> I["TextBlock interne<br/>{Binding #Racine.Nom}"]
Pourquoi une StyledProperty ?
Une simple propriété C# ne supporte ni binding, ni style, ni animation. Une StyledProperty oui.
Options d'une propriété¶
public static readonly StyledProperty<int> NoteProperty =
AvaloniaProperty.Register<Etoiles, int>(
nameof(Note),
defaultValue: 0,
defaultBindingMode: BindingMode.TwoWay, // comme TextBox.Text
coerce: (_, v) => Math.Clamp(v, 0, 5)); // borne la valeur
Réagir au changement¶
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == NoteProperty)
{
var ancienne = change.GetOldValue<int>();
var nouvelle = change.GetNewValue<int>();
MettreAJourEtoiles(nouvelle);
}
}
Déclencher un nouveau rendu / layout¶
static Etoiles()
{
AffectsRender<Etoiles>(NoteProperty, CouleurProperty);
AffectsMeasure<Etoiles>(TailleProperty);
}
Propriété directe (non stylable, plus légère)¶
private int _nombre;
public static readonly DirectProperty<Compteur, int> NombreProperty =
AvaloniaProperty.RegisterDirect<Compteur, int>(nameof(Nombre), o => o.Nombre);
public int Nombre
{
get => _nombre;
private set => SetAndRaise(NombreProperty, ref _nombre, value);
}
Propriété attachée¶
public class Aide : AvaloniaObject
{
public static readonly AttachedProperty<string?> TexteProperty =
AvaloniaProperty.RegisterAttached<Aide, Control, string?>("Texte");
public static string? GetTexte(Control c) => c.GetValue(TexteProperty);
public static void SetTexte(Control c, string? v) => c.SetValue(TexteProperty, v);
}
TemplatedControl¶
Le comportement (C#) et l'apparence (ControlTheme) sont séparés : on peut redessiner le contrôle sans toucher au code.
flowchart LR
subgraph C["Alerte.cs (comportement)"]
P["Message, EstCritique"]
E["événement Fermee"]
PC["pseudo-classe :critique"]
end
subgraph T["Alerte.axaml (apparence)"]
TP["Template : Border + TextBlock + PART_Fermer"]
S["^:critique → rouge"]
end
C -- "OnApplyTemplate trouve PART_Fermer" --> T
T -- "TemplateBinding Message" --> C
Connexion rétablie.✕
Disque presque plein !✕
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
namespace MonApp.Controls;
[TemplatePart("PART_Fermer", typeof(Button))]
[PseudoClasses(":critique")]
public class Alerte : TemplatedControl
{
public static readonly StyledProperty<string?> MessageProperty =
AvaloniaProperty.Register<Alerte, string?>(nameof(Message));
public static readonly StyledProperty<bool> EstCritiqueProperty =
AvaloniaProperty.Register<Alerte, bool>(nameof(EstCritique));
public static readonly RoutedEvent<RoutedEventArgs> FermeeEvent =
RoutedEvent.Register<Alerte, RoutedEventArgs>(nameof(Fermee), RoutingStrategies.Bubble);
public string? Message { get => GetValue(MessageProperty); set => SetValue(MessageProperty, value); }
public bool EstCritique { get => GetValue(EstCritiqueProperty); set => SetValue(EstCritiqueProperty, value); }
public event EventHandler<RoutedEventArgs> Fermee
{
add => AddHandler(FermeeEvent, value);
remove => RemoveHandler(FermeeEvent, value);
}
private Button? _fermer;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (_fermer is not null) _fermer.Click -= OnFermer;
_fermer = e.NameScope.Find<Button>("PART_Fermer");
if (_fermer is not null) _fermer.Click += OnFermer;
}
private void OnFermer(object? sender, RoutedEventArgs e)
{
IsVisible = false;
RaiseEvent(new RoutedEventArgs(FermeeEvent));
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == EstCritiqueProperty)
PseudoClasses.Set(":critique", EstCritique);
}
}
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="using:MonApp.Controls">
<ControlTheme x:Key="{x:Type c:Alerte}" TargetType="c:Alerte">
<Setter Property="Background" Value="#EFF6FF" />
<Setter Property="BorderBrush" Value="#3B82F6" />
<Setter Property="Padding" Value="12" />
<Setter Property="Template">
<ControlTemplate>
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="4,0,0,0" CornerRadius="4"
Padding="{TemplateBinding Padding}">
<DockPanel>
<Button x:Name="PART_Fermer" DockPanel.Dock="Right" Content="✕"
Background="Transparent" Padding="4" />
<TextBlock Text="{TemplateBinding Message}" TextWrapping="Wrap"
VerticalAlignment="Center" />
</DockPanel>
</Border>
</ControlTemplate>
</Setter>
<Style Selector="^:critique">
<Setter Property="Background" Value="#FEF2F2" />
<Setter Property="BorderBrush" Value="#EF4444" />
</Style>
</ControlTheme>
</ResourceDictionary>
Hériter d'un contrôle existant¶
public class TextBoxNumerique : TextBox
{
// Réutilise le thème de TextBox
protected override Type StyleKeyOverride => typeof(TextBox);
protected override void OnTextInput(TextInputEventArgs e)
{
if (e.Text is { } t && !t.All(char.IsDigit))
{
e.Handled = true; // refuse le caractère
return;
}
base.OnTextInput(e);
}
}
Sans lui, le contrôle dérivé n'a aucun thème et s'affiche vide.
Validation des données v12¶
Une propriété enregistrée avec enableDataValidation: true affiche les erreurs de binding automatiquement :
public static readonly StyledProperty<string?> ValeurProperty =
AvaloniaProperty.Register<MonChamp, string?>(nameof(Valeur), enableDataValidation: true);
Supprimez les surcharges de UpdateDataValidation qui ne faisaient qu'appeler DataValidationErrors.SetError.