Skip to content

Instantly share code, notes, and snippets.

@jtheisen
Created January 11, 2014 23:34
Show Gist options
  • Save jtheisen/8378401 to your computer and use it in GitHub Desktop.
Save jtheisen/8378401 to your computer and use it in GitHub Desktop.
Programmatic type-safe bindings
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