Created
January 11, 2014 23:34
-
-
Save jtheisen/8378401 to your computer and use it in GitHub Desktop.
Programmatic type-safe bindings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq.Expressions; | |
using System.Windows; | |
using System.Windows.Data; | |
namespace MonkeyBusters | |
{ | |
public static class ObservableDependencyValue | |
{ | |
public static ObservableDependencyValue<T> Create<T>(Expression<Func<T>> expr, BindingMode mode = BindingMode.OneWay) | |
{ | |
return new ObservableDependencyValue<T>().Bind(expr, mode); | |
} | |
} | |
public class ObservableDependencyValue<T> : DependencyObject | |
{ | |
#region T ObservableDependencyValue<T>.Value = default(T) | |
#region Boilerplate | |
public T Value | |
{ | |
get { return (T)GetValue(ValueProperty); } | |
set { SetValue(ValueProperty, value); } | |
} | |
public static readonly DependencyProperty ValueProperty = | |
DependencyProperty.Register("Value", typeof(T), typeof(ObservableDependencyValue<T>), new PropertyMetadata(default(T), StaticHandleValueChanged)); | |
static void StaticHandleValueChanged(DependencyObject self, DependencyPropertyChangedEventArgs args) | |
{ | |
((ObservableDependencyValue<T>)self).HandleValueChanged((T)args.OldValue, (T)args.NewValue); | |
} | |
#endregion | |
void HandleValueChanged(T oldValue, T value) | |
{ | |
Notify(); | |
} | |
#endregion | |
public ObservableDependencyValue() | |
{ | |
} | |
public ObservableDependencyValue(BindingBase bindingBase) | |
{ | |
Bind(bindingBase); | |
} | |
public ObservableDependencyValue<T> Bind(BindingBase bindingBase) | |
{ | |
BindingOperations.SetBinding(this, ValueProperty, bindingBase); | |
return this; | |
} | |
public ObservableDependencyValue<T> Bind(Expression<Func<T>> expr, BindingMode mode = BindingMode.OneWay) | |
{ | |
var path = RootedPropertyPath.Create(expr); | |
return Bind(new Binding(path.Path) { Source = path.Target, Mode = mode }); | |
} | |
public void Notify() | |
{ | |
if (ValueChanged != null) ValueChanged(Value); | |
} | |
public event Action<T> ValueChanged; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment