1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class BindToEverythingBehavior
{
#region Attached Property string Property
public static string GetProperty(DependencyObject obj)
{
return ( string )obj.GetValue(PropertyProperty);
}
public static void SetProperty(DependencyObject obj, string value)
{
obj.SetValue(PropertyProperty, value);
}
public static readonly DependencyProperty PropertyProperty =
DependencyProperty.RegisterAttached("Property", typeof(string), typeof(BindToEverythingBehavior), new UIPropertyMetadata(null));
#endregion
#region Attached Property object Value
public static object GetValue(DependencyObject obj)
{
return ( object )obj.GetValue(ValueProperty);
}
public static void SetValue(DependencyObject obj, object value)
{
obj.SetValue(ValueProperty, value);
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.RegisterAttached("Value", typeof(object), typeof(BindToEverythingBehavior),
new UIPropertyMetadata(null, BindToEverythingBehavior.OnValueChanged));
#endregion
static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
string propertyName = GetProperty(obj);
if ( string.IsNullOrEmpty(propertyName) == false ) {
var prop = obj.GetType().GetProperty(propertyName);
if ( prop == null )
throw new ArgumentNullException("property '" + propertyName + "' not found");
prop.SetValue(obj, Convert.ChangeType(e.NewValue, prop.PropertyType), null);
}
}
} |
Partager