summaryrefslogtreecommitdiff
path: root/Juick/Classes/DependencyPropertyListener.cs
blob: 693c16ad65f68b9948f524f211603b554d272c93 (plain) (blame)
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
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Windows;
using System.Windows.Data;

namespace Juick.Classes
{
    public class DependencyPropertyListener
    {
        static int index;
        
        readonly DependencyProperty property;
        FrameworkElement target;
        public event EventHandler<BindingChangedEventArgs> Changed;

        public DependencyPropertyListener()
        {
            property = DependencyProperty.RegisterAttached(
                "DependencyPropertyListener" + DependencyPropertyListener.index++,
                typeof(object),
                typeof(DependencyPropertyListener),
                new PropertyMetadata(null, new PropertyChangedCallback(HandleValueChanged)));
        }
        
        public void Attach(FrameworkElement element, Binding binding)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (target != null)
            {
                throw new InvalidOperationException("Cannot attach an already attached listener");
            }
            target = element;
            target.SetBinding(property, binding);
        }
        
        public void Detach()
        {
            target.ClearValue(property);
            target = null;
        }
        
        void HandleValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (Changed != null)
            {
                Changed.Invoke(this, new BindingChangedEventArgs(e));
            }
        }
    }
}