using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace IFramework { /// /// 绑定对象 /// public abstract class BindableObject : Unit { /// /// 绑定方式 /// public enum BindOperation { /// /// 监听+发布 /// Both, /// /// 监听 /// Listen, } /// /// 绑定方式 /// public BindOperation bindOperation = BindOperation.Both; private Dictionary> _callmap; /// /// ctor /// protected BindableObject() { _callmap = new Dictionary>(); } /// /// 注册监听 /// /// /// public void Subscribe(string propertyName, Action listener) { if (!_callmap.ContainsKey(propertyName)) _callmap.Add(propertyName, null); _callmap[propertyName] += listener; } /// /// 移除监听 /// /// /// public void UnSubscribe(string propertyName, Action listener) { if (!_callmap.ContainsKey(propertyName)) return; _callmap[propertyName] -= listener; if (_callmap[propertyName] == null) _callmap.Remove(propertyName); } /// /// 获取属性 /// /// /// /// /// protected T GetProperty(ref T property, [CallerMemberName]string propertyName = "") { if (BindableObjectHandler.handler != null) { //if (string.IsNullOrEmpty(propertyName)) // propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name); BindableObjectHandler.handler.Subscribe(this, typeof(T), propertyName); } return property; } /// /// 设置属性 /// /// /// /// /// protected void SetProperty(ref T property, T value, [CallerMemberName]string propertyName = "") { if (EqualityComparer.Default.Equals(property, value)) return; //if (string.IsNullOrEmpty(propertyName)) // propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name); property = value; //if (bindOperation == BindOperation.Listen) return; PublishPropertyChange(propertyName, value); } private void PublishPropertyChange(string propertyName, object obj) { if (!_callmap.ContainsKey(propertyName)) return; if (_callmap[propertyName] == null) return; _callmap[propertyName].Invoke(propertyName, obj); } /// /// 释放 /// protected override void OnDispose() { _callmap.Clear(); _callmap = null; } //private string GetProperyName(string methodName) //{ // if (methodName.StartsWith("get_") || methodName.StartsWith("set_") || // methodName.StartsWith("put_")) // { // return methodName.Substring("get_".Length); // } // throw new Exception(methodName + " not a method of Property"); //} } }