using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace Tango.SharedUI
{
/// <summary>
/// Represents a binding event container.
/// </summary>
/// <seealso cref="System.Windows.DependencyObject" />
public class BindingEventContainer : DependencyObject
{
private Action _renewAction;
/// <summary>
/// Occurs when the dependency property value has changed.
/// </summary>
public event EventHandler<BindingEventArgs> ValueChanged;
/// <summary>
/// Gets or sets the value.
/// </summary>
public Object Value
{
get { return (Object)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(Object), typeof(BindingEventContainer), new PropertyMetadata(null, (d, e) => (d as BindingEventContainer).OnValueChanged()));
/// <summary>
/// Gets or sets the binding property.
/// </summary>
public BindingProperty BindingProperty { get; set; }
/// <summary>
/// Gets or sets the dependency object.
/// </summary>
public DependencyObject DependencyObject { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BindingEventContainer"/> class.
/// </summary>
/// <param name="takeElement">The dependency object.</param>
/// <param name="bindingProperty">The binding property.</param>
public BindingEventContainer(DependencyObject dependencyObject, BindingProperty bindingProperty)
{
DependencyObject = dependencyObject;
BindingProperty = bindingProperty;
}
/// <summary>
/// Called when the value has been changed
/// </summary>
protected virtual void OnValueChanged()
{
ValueChanged?.Invoke(this, new BindingEventArgs()
{
BindingProperty = BindingProperty,
DependencyObject = DependencyObject,
Value = Value,
_renewAction = _renewAction
});
}
/// <summary>
/// Generates a new <see cref="BindingEventContainer"/> for the specified Take element and binding property.
/// </summary>
/// <param name="dependencyObject">The take element.</param>
/// <param name="dependencyProperty">The binding property.</param>
/// <returns></returns>
public static BindingEventContainer Generate(DependencyObject dependencyObject, DependencyProperty dependencyProperty)
{
BindingEventContainer container = new BindingEventContainer(dependencyObject, new BindingProperty(dependencyProperty));
container._renewAction = () =>
{
Binding binding = new Binding();
binding.Mode = BindingMode.OneWay;
binding.Source = dependencyObject;
binding.Path = new PropertyPath(dependencyProperty);
BindingOperations.SetBinding(container, BindingEventContainer.ValueProperty, binding);
};
container._renewAction.Invoke();
return container;
}
}
}