Aller au contenu

Bases du binding

Toutes les formes de {Binding}, de la plus simple à la plus avancée.

Chemin

<TextBlock Text="{Binding Nom}" />                    <!-- propriété -->
<TextBlock Text="{Binding Client.Adresse.Ville}" />   <!-- chemin -->
<TextBlock Text="{Binding Tags[0]}" />                <!-- indexeur -->
<TextBlock Text="{Binding Notes[maths]}" />           <!-- dictionnaire -->
<TextBlock Text="{Binding}" />                        <!-- le DataContext lui-même -->
<TextBlock Text="{Binding Path=Nom}" />               <!-- forme longue -->

Modes

<TextBlock Text="{Binding Nom}" />                         <!-- OneWay (défaut pour la plupart) -->
<TextBox Text="{Binding Nom}" />                           <!-- TwoWay (défaut pour TextBox.Text) -->
<TextBox Text="{Binding Nom, Mode=OneTime}" />             <!-- lu une seule fois -->
<TextBox Text="{Binding Recherche, Mode=OneWayToSource}" /><!-- vue → ViewModel seulement -->

ViewModel Vue OneWay TwoWay OneTime (au chargement seulement) OneWayToSource

Aperçu · tapez dans chaque champ du haut
TwoWay : les deux champs sont liés à la même propriété Nom
OneWay : le TextBlock suit, mais on ne peut pas le modifier
Ada
Mode Sens
OneWay ViewModel → vue
TwoWay dans les deux sens
OneTime une fois, au chargement
OneWayToSource vue → ViewModel

Quand mettre à jour la source

<!-- Par défaut : à chaque frappe -->
<TextBox Text="{Binding Nom}" />

<!-- À la perte du focus -->
<TextBox Text="{Binding Nom, UpdateSourceTrigger=LostFocus}" />

Pour une recherche « anti-rebond », voir Threads et async.

Formater

<TextBlock Text="{Binding Prix, StringFormat='{}{0:C2}'}" />
<TextBlock Text="{Binding Date, StringFormat='Le {0:d MMMM yyyy}'}" />
<TextBlock Text="{Binding Pourcentage, StringFormat='{}{0:P1}'}" />
<TextBlock Text="{Binding Quantite, StringFormat='{}{0} article(s)'}" />

Valeurs de repli

flowchart LR
  B["{Binding Client.Nom}"] --> Q1{"chemin<br/>résolu ?"}
  Q1 -- "non (Client = null…)" --> F["FallbackValue<br/>« Inconnu »"]
  Q1 -- oui --> Q2{"valeur = null ?"}
  Q2 -- oui --> N["TargetNullValue<br/>« (aucun commentaire) »"]
  Q2 -- non --> V["la vraie valeur"]
<!-- Si le chemin est introuvable ou en erreur -->
<TextBlock Text="{Binding Client.Nom, FallbackValue='Inconnu'}" />

<!-- Si la valeur est null -->
<TextBlock Text="{Binding Commentaire, TargetNullValue='(aucun commentaire)'}" />

Négation

<TextBlock Text="Aucun résultat" IsVisible="{Binding !Resultats.Count}" />
<Button IsEnabled="{Binding !EstOccupe}" Content="Envoyer" />```

## Lier à un autre élément

<div class="av-demo"><div class="av-demo__barre"><span>Aperçu · ScaleX/ScaleY liés à #Zoom.Value</span></div><div class="av-demo__scene av-ui av-pile" style="gap:10px"><input type="range" min="0.5" max="3" step="0.1" value="1" style="max-width:300px" oninput="this.nextElementSibling.firstElementChild.style.transform='scale('+this.value+')'"><div style="height:110px;overflow:hidden;border:1px dashed var(--av-ctrl-border);border-radius:4px;display:grid;place-items:center"><div class="av-paysage" style="width:100px;height:50px;background-size:cover;transition:transform .1s"></div></div></div></div>

```xml
<Slider x:Name="Zoom" Minimum="0.5" Maximum="3" Value="1" />
<Image Source="/Assets/plan.png">
  <Image.RenderTransform>
    <ScaleTransform ScaleX="{Binding #Zoom.Value}" ScaleY="{Binding #Zoom.Value}" />
  </Image.RenderTransform>
</Image>

#Nom = élément nommé.

Lier à un parent

flowchart BT
  T["TextBlock<br/>$self"] --> B1["Border (le 1er : $parent[Border])"]
  B1 --> B2["Border (le 2e : index 1)"]
  B2 --> W["Window ($parent[Window])"]
<!-- Le premier ancêtre de type Window -->
<TextBlock Text="{Binding $parent[Window].Title}" />

<!-- Le deuxième ancêtre Border -->
<TextBlock Tag="{Binding $parent[Border;1].Tag}" />

<!-- L'élément lui-même -->
<TextBlock Text="{Binding $self.Bounds.Width}" />

Commande du ViewModel parent depuis une liste

<ListBox ItemsSource="{Binding Taches}">
  <ListBox.ItemTemplate>
    <DataTemplate x:DataType="m:Tache">
      <DockPanel>
        <Button DockPanel.Dock="Right" Content="✕"
                Command="{Binding $parent[ListBox].((vm:MainViewModel)DataContext).SupprimerCommand}"
                CommandParameter="{Binding}" />
        <TextBlock Text="{Binding Titre}" />
      </DockPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Le cast (vm:MainViewModel) est nécessaire avec les compiled bindings.

Source explicite

<TextBlock Text="{Binding Source={x:Static local:Infos.Version}}" />
<TextBlock Text="{Binding Length, Source={StaticResource Bienvenue}}" />

MultiBinding

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat="{}{0} {1}">
      <Binding Path="Prenom" />
      <Binding Path="Nom" />
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

Avec un convertisseur : voir Convertisseurs.

Classes et propriétés conditionnelles

<Border Classes.selectionne="{Binding EstSelectionne}"
        Classes.erreur="{Binding !EstValide}" />

Binding en C

// v12 : compilé, typé
texte.Bind(TextBlock.TextProperty,
    CompiledBinding.Create((MainViewModel vm) => vm.Titre));

// Par réflexion (chemin texte)
texte.Bind(TextBlock.TextProperty, new ReflectionBinding(nameof(MainViewModel.Titre)));

// Vers un autre contrôle
texte[!TextBlock.TextProperty] = saisie[!TextBox.TextProperty];

Déboguer un binding

Les erreurs de binding apparaissent dans la sortie Debug grâce à .LogToTrace(). Pour plus de détails :

.LogToTrace(LogEventLevel.Debug, LogArea.Binding)