-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataBinder.cs
84 lines (72 loc) · 3.12 KB
/
DataBinder.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DataBinding
{
/// <summary>
/// Glues the view and view model together based on the binding attributes of the view.
/// </summary>
public class DataBinder
{
private object mView;
private INotifyPropertyChanged mModel;
private List<Action> mUnbindActions = new List<Action>();
public bool BindingsApplied { get; private set; }
public DataBinder( object view, INotifyPropertyChanged model )
{
this.mView = view;
this.mModel = model;
this.BindingsApplied = false;
}
public void ApplyBindings()
{
if ( !this.BindingsApplied && this.mModel != null && this.mModel is INotifyPropertyChanged )
{
var bundedMembers = this.GetBoundedMembers( this.mView );
foreach ( var memberInfo in bundedMembers )
{
var bindingAttributes = memberInfo.GetCustomAttributes( false ).ToList().Select( item => item as BindingAttribute );
foreach ( var bindingAttribute in bindingAttributes )
{
var control = GetControl( memberInfo );
var unbind = bindingAttribute.Bind( control, this.mModel );
this.mUnbindActions.Add( unbind );
}
}
this.BindingsApplied = true;
}
}
public void DetachBindings()
{
if ( this.BindingsApplied )
{
this.mUnbindActions.ForEach( action => action.Invoke() );
this.mUnbindActions.Clear();
this.BindingsApplied = false;
}
}
private object GetControl( MemberInfo memberInfo )
{
return memberInfo is FieldInfo ?
( memberInfo as FieldInfo ).GetValue( this.mView ) :
( memberInfo as PropertyInfo ).GetValue( this.mView, null );
}
private IEnumerable<MemberInfo> GetBoundedMembers( object view )
{
var members = new List<MemberInfo>();
var fields = view.GetType().GetFields( System.Reflection.BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
members.AddRange( fields );
var properties = view.GetType().GetProperties( System.Reflection.BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
members.AddRange( properties );
return members.Where( memberInfo =>
memberInfo.IsDefined( typeof( OneWayBinding ), false ) ||
memberInfo.IsDefined( typeof( OneTimeBinding ), false ) ||
memberInfo.IsDefined( typeof( TwoWayBinding ), false ) ||
memberInfo.IsDefined( typeof( OneWayToSourceBinding ), false ) ||
memberInfo.IsDefined( typeof( CommandBinding ), false ) ).ToList();
}
}
}