Bienvenue à Blogs CodeS-SourceS Identification | Inscription | Aide

Frédéric Hamel

Assert.Success();

[WPF] Data Binding Quick Reference

Vous trouverez ici les principales syntaxes permettant de réaliser un Data Binding en WPF. Le but ici n'est pas d'expliquer en détail son mécanisme mais plutôt de proposer une référence où vous pourrez trouver la syntaxe qui correspondra à votre besoin.

Sommaire :

  1. Affecter la source d'un binding
  2. Affiner la sélection avec la propriété Path
  3. Mode du Binding
  4. Utiliser des Converters
  5. Quelques astuces pour le Binding
  6. Utiliser le MultiBinding
  7. Rendre ses objets .NET Binding-Friendly

Affecter la source d'un binding

  • Binding sur le DataContext
    <ListBox ItemsSource="{Binding}" />
  • Binding sur un autre élément

    <Slider Name="_mySlider"/>
    <TextBlock Text="{Binding ElementName=_mySlider,Path=Value}"/>
  • Binding sur soi-même
    <TextBlock Name="_selfName" 
     Text="{Binding Name, RelativeSource={RelativeSource Self}}" />
  • Binding vers un parent
    <Canvas Name="_canvas">
        <TextBlock Text="{Binding Path=Name, 
                                  RelativeSource=
     {RelativeSource FindAncestor, AncestorType={x:Type Canvas}}}" />
    </Canvas>
  • Binding vers le template parent
    <ControlTemplate x:Key="_template">
        <TextBlock Background="{TemplateBinding Background}"/>
    </ControlTemplate>
  • Binding vers le data item précédent
     {Binding RelativeSource={RelativeSource PreviousData}}
  • Binding d'une propriété statique
    <TextBlock Text="{x:Static local:Window1.AStaticProperty}"/>
  • Binding d'une ressource statique
    <TextBlock Background="{StaticResource _blackBrush}"/>
  • Binding d'une ressource dynamique
    <TextBlock Background="{DynamicResource _blackBrush}"/>

Affiner la sélection avec la propriété Path

  • Deuxième constructeur de la classe Binding
    <!--Use the constructor : public Binding(string path)-->
    <TextBlock Text="{Binding Name}"/>
  • Propriété Path

    <TextBlock Text="{Binding Path=Name}"/>
  • Syntaxe longue
    <TextBlock>
        <TextBlock.Text>
            <Binding>
                <Binding.Path>Name</Binding.Path>
            </Binding>
        </TextBlock.Text>
    </TextBlock>
  • Binding vers une DependencyProperty attachée
    <TextBlock Canvas.Left="50" 
               Text="{Binding Path=(Canvas.Left), 
    RelativeSource={RelativeSource Self}}" />
  • Binding vers l'item courant synchronisé
<TextBlock Text="{Binding Path=/}" />
<TextBlock Text="{Binding Path=Photos/}" />
<TextBlock Text="{Binding Path=/DateTime}" />
<TextBlock Text="{Binding Path=Photos/DateTime}" />

Mode du Binding

  • Bidirectionnel
    <TextBlock Text="{Binding Path=Name, Mode=TwoWay}"/>
  • De la source vers la target
    <TextBlock Text="{Binding Path=Name, Mode=OneWay}"/>
  • Une fois de la source vers la target
    <TextBlock Text="{Binding Path=Name, Mode=OneTime}"/>
  • De la target vers la source
    <TextBlock Text="{Binding Path=Name, Mode=OneWayToSource}"/>

Utiliser des Converters

  • Affecter un Converter
    <TextBlock Text="{Binding Name, 
        Converter={StaticResource myDoNothingConverter}}"/>
  • Passer des paramètres à un Converter
    <TextBlock Text="{Binding Name, 
        Converter={StaticResource myDoNothingConverter},
        ConverterParameter='Hello'}"/>
  • Écrire un Converter
    En Xaml:
    xmlns
    :local="clr-namespace:Wpf.BindingLibrary.QuickReference"
    <local:DoNothingConverter x:Key="myDoNothingConverter"/>
    En Code:
    namespace
    Wpf.BindingLibrary.QuickReference { public class DoNothingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return Binding.DoNothing; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
  • Écrire un Converter multi-values
    public class MultiValueConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, 
            object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes,
            object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
  • Utiliser le string formater converter, disponible bientôt dans le SP1 de .NET 3.5
     Lire le post de Lester à ce sujet

Quelques astuces pour le binding

  • Récupérer un Binding
    BindingOperations.
    GetBindingExpression(dependencyObject, TextBlock.TextProperty); BindingOperations.
    GetBinding(dependencyObject, TextBlock.TextProperty);
  • Mettre à jour un Binding
    var bindingExpression =
    BindingOperations.
    GetBindingExpression(dependencyObject, TextBlock.TextProperty); binding.UpdateSource(); binding.UpdateTarget();
  • Effacer un Binding
    BindingOperations.
    ClearBinding(dependencyObject,TextBlock.TextProperty); BindingOperations.ClearAllBindings(dependencyObject);
  • Ne rien faire pendant un Binding
    return Binding.DoNothing;

Utiliser le MultiBinding

  • Syntaxe
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding 
    Converter="{StaticResource myMultiValueConverter}"> <Binding Path="Name"/> <Binding Path="Adress"/> </MultiBinding> </TextBlock.Text> </TextBlock>

Rendre ses objets .NET Binding-friendly

  • INotifyPropertyChanged
    public class Person : INotifyPropertyChanged
    {
        [field:NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void RaisePropertyChanged(string propertyName) 
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
            }
        }
    
        private string _name;
        public string Name { get { return _name; }
            set {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
    }
  • ObservableCollection<T>
    Vous pouvez utiliser le deuxième constructeur avec votre liste existante
    public ObservableCollection(List<T> list);
Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :
Posted: dimanche 1 juin 2008 22:31 par fredhamel
Classé sous : , , , ,

Commentaires

zogstrip a dit :

Excellent !

Merci pour cet article clair !

# juin 2, 2008 01:46

Thomas LEBRUN a dit :

Dans le binding vers un parent, tu as en oublié un: http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.ancestorlevel.aspx :)

Sinon, c'est un bon récapitulatif, toujours bon à garder sous le coude !

# juin 2, 2008 08:36

fredhamel a dit :

Hello Thomas, merci pour l'ajout.

Le lecteur attentif aura noté aussi qu'il manque le binding avec du Xml, ou asynchrone par exemple...

Cela fera surement l'objet d'un prochain post :)

# juin 2, 2008 09:05
Les commentaires anonymes sont désactivés

Les 10 derniers blogs postés

- Dell Inspiron Mini 9 - Enfin en vente !!! par The diary of EBArtSoft le il y a 13 heures et 28 minutes

- Solution Template et Project Template dans Visual Studio par Atteint de JavaScriptite Aiguë [Cyril Durand] le il y a 16 heures et 10 minutes

- PocketIE et Assignation du SRC d'un Element IMG par Jerome Laban le il y a 17 heures et 2 minutes

- Conversion de fichiers RAW en fichier JPEG avec WPF par Perspective le il y a 17 heures et 38 minutes

- Mise à Jour du Moteur de Recherche des Arrêts de Bus de Montréal par Jerome Laban le il y a 18 heures et 22 minutes

- [WPF] XPSReader v0.2 par Blog Technique d'Audrey PETIT le il y a 19 heures et 23 minutes

- Entity Framework : providers Oracle, MySQL et PostgreSQL par Matthieu MEZIL le 09-07-2008, 10:10

- [WPF] Nouvel article sur c2i.fr par Richard Clark le 09-06-2008, 17:33

- F# nouvelle CTP 1.9.6.2 (update) par Pierrick's Blog le 09-06-2008, 13:27

- La suite ...Proposition de collaboration rédactionnelle entre les communautés de développeurs et Microsoft France par LucasR le 09-05-2008, 17:45