[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 :
- Affecter la source d'un binding
- Affiner la sélection avec la propriété Path
- Mode du Binding
- Utiliser des Converters
- Quelques astuces pour le Binding
- Utiliser le MultiBinding
- Rendre ses objets .NET Binding-Friendly
- 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}}
- 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}" />
- 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}"/>
- 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
- 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;
- 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 :