using System.Windows;
using System.Windows.Data;
namespace Developpez.Dotnet.Windows
{
///
/// Fournit des méthodes pour faciliter l'évaluation d'une propriété
/// d'un objet d'après son chemin
///
public static class PropertyPathHelper
{
///
/// Renvoie la valeur de la propriété dont le chemin est spécifié pour l'objet spécifié
///
/// Objet pour lequel on souhaite évaluer la propriété
/// Chemin de la propriété
/// La valeur de la propriété
public static object GetValue(object obj, string propertyPath)
{
Binding binding = new Binding(propertyPath);
binding.Mode = BindingMode.OneTime;
binding.Source = obj;
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
return _dummy.GetValue(Dummy.ValueProperty);
}
///
/// Affecte une valeur à la propriété dont le chemin est spécifiée pour l'objet spécifié
///
/// Objet pour lequel on souhaite affecter la propriété
/// Chemin de la propriété
/// Valeur à affecter
public static void SetValue(object obj, string propertyPath, object value)
{
Binding binding = new Binding(propertyPath);
binding.Mode = BindingMode.OneWayToSource;
binding.Source = obj;
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
_dummy.SetValue(Dummy.ValueProperty, value);
}
private static readonly Dummy _dummy = new Dummy();
private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
}
}
}