using System; using System.Collections.Generic; using System.Text; using System.Collections.Concurrent; using System.Linq; using System.ComponentModel; using System.Reflection; using CPF.Reflection; using System.Timers; using CPF.Controls; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Linq.Expressions; using System.Threading; using System.Diagnostics; namespace CPF { /// /// 绑定 /// public class Binding : IDisposable { static ConcurrentDictionary> notifys = new ConcurrentDictionary>(); static Thread GCTimer; //internal static bool runGC = true; /// /// 事件弱绑定 /// /// /// 不能是静态方法 public static void RegisterPropertyChanged(INotifyPropertyChanged notify, PropertyChangedEventHandler propertyChanged) { if (propertyChanged.Method.IsStatic) { throw new Exception("不能是静态方法,必须关联对象"); } if (GCTimer == null) { GCTimer = new Thread(GCTimer_Elapsed); GCTimer.IsBackground = true; GCTimer.Name = "清理无效绑定"; GCTimer.Start(); } if (!notifys.TryGetValue(new WeakNode(notify), out HashSet list)) { notify.PropertyChanged += Notify_PropertyChanged; list = new HashSet(); notifys.TryAdd(new WeakNode(notify), list); } list.Add(new WeakDelegate(propertyChanged.Target, propertyChanged.Method)); } private static void GCTimer_Elapsed() { while (true) { Thread.Sleep(5000); List remove = new List(); foreach (var item in notifys) { //if(!item.Key.reference.IsAlive) if (!item.Key.reference.TryGetTarget(out INotifyPropertyChanged notifyProperty) || (notifyProperty is IDisposed cpf && cpf.IsDisposed)) { remove.Add(item.Key); } } if (remove.Count > 0) { foreach (var item in remove) { notifys.TryRemove(item, out _); } GC.Collect(); } } } private static void Notify_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (notifys.TryGetValue(new WeakNode((INotifyPropertyChanged)sender), out HashSet list)) { List ids = new List(); List invokes = new List(); foreach (var item in list) { item.reference.TryGetTarget(out var t); if (t == null || (t is IDisposed cpf && cpf.IsDisposed)) { ids.Add(item); } else { //item.method.FastInvoke(t, sender, e); invokes.Add(item); } } foreach (var item in invokes) { item.reference.TryGetTarget(out var t); if (t == null) { ids.Add(item); } else { item.method.FastInvoke(t, sender, e); } } for (int i = 0; i < ids.Count; i++) { list.Remove(ids[i]); } } } /// /// 移除弱事件绑定 /// /// /// public static void CancellationPropertyChanged(INotifyPropertyChanged notify, PropertyChangedEventHandler propertyChanged) { var node = new WeakNode(notify); if (notifys.TryGetValue(node, out HashSet list)) { List ids = new List(); var wd = new WeakDelegate(propertyChanged.Target, propertyChanged.Method); if (list.Contains(wd)) { ids.Add(wd); } //foreach (var item in list) //{ // //var t = item.reference.Target; // //if (t == null || (propertyChanged.Target == t && propertyChanged.Method == item.method)) // if (!item.reference.IsAlive) // { // ids.Add(item); // } //} if (ids.Count == list.Count) { list.Clear(); } else { for (int i = 0; i < ids.Count; i++) { list.Remove(ids[i]); } } if (list.Count == 0) { notifys.TryRemove(node, out _); notify.PropertyChanged -= Notify_PropertyChanged; } } } struct WeakNode { public WeakNode(INotifyPropertyChanged reference) { this.reference = new WeakReference(reference); hash = reference.GetHashCode(); } public WeakReference reference; public override bool Equals(object obj) { if (obj is WeakNode n) { n.reference.TryGetTarget(out INotifyPropertyChanged t1); reference.TryGetTarget(out INotifyPropertyChanged t2); if (t1 == null) { return t1 == t2; } return t1.Equals(t2); } return false; } readonly int hash; public override int GetHashCode() { //if (hash == 0 && reference.TryGetTarget(out INotifyPropertyChanged t)) //{ // hash = t.GetHashCode(); // return hash; //} return hash; } } CpfObject owner; /// /// Target对象 /// public CpfObject Owner { get { return owner; } internal set { //if (value == null && !unbind) //{ // throw new Exception("错误"); //} owner = value; } } /// /// 数据源对象 /// public WeakReference Source { get; internal set; } internal Binding(object sObj, string sourcePropertyName, string targetPropertyName, BindingMode bindingMode) { if (sObj != null) { Source = new WeakReference(sObj); IsDataContext = false; } TargetPropertyName = targetPropertyName; SourcePropertyName = sourcePropertyName; BindingMode = bindingMode; } internal Binding() { } /// /// 多级绑定的属性集合 /// string[] sourcePropertyNames; internal bool IsDataContext = true; string sourcePropertyName; /// /// 数据源字段名 /// public string SourcePropertyName { get { return sourcePropertyName; } internal set { sourcePropertyName = value; if (value != null) { sourcePropertyNames = SourcePropertyName.Split('.'); } else { sourcePropertyNames = null; } } } /// /// 链式绑定下标 /// public int SourcePropertyIndex { get; internal set; } = 0; /// /// Owner被绑定的属性名 /// public string TargetPropertyName { get; internal set; } /// /// SourceToTarget异常回调 /// public Action SourceToTargetError { get; set; } /// /// TargetToSource异常回调 /// public Action TargetToSourceError { get; set; } /// /// 数据绑定的转换 /// public Func Convert { get; set; } /// /// 数据绑定的转换 /// public Func ConvertBack { get; set; } /// /// 绑定模式 /// public BindingMode BindingMode { get; internal set; } //bool unbind; /// /// 取消数据绑定 /// public void UnBind() { //unbind = true; if (Owner != null) { List list; if (Owner.Bindings.binds.TryGetValue(TargetPropertyName, out list)) { list.Remove(this); } if (list != null && list.Count == 0) { Owner.Bindings.binds.Remove(TargetPropertyName); } } if (Source != null) { if (Source.IsAlive) { INotifyPropertyChanged n = Source.Target as INotifyPropertyChanged; if (n != null) { //n.PropertyChanged -= PropertyChanged; CancellationPropertyChanged(n); } } } Source = null; Owner = null; //unbind = false; } ///// ///// 绑定是否有效 ///// //public bool IsValid //{ // get; internal set; //} static Stack current = new Stack(); /// /// 当前执行的绑定对象 /// public static Binding Current { get { if (current.Count == 0) { return null; } return current.Peek(); } } bool cancel = false; /// /// 取消这次的数据传递 /// public void Cancel() { cancel = true; } /// /// 是否是双向绑定的时候回传状态,一般在转换器里使用,在双向绑定的时候,假如label1和label2的text双向绑定了 label1.Text="1";那label1的Text会传给label2的Text,但是这个同时label2的Text也会因为绑定的缘故往label1传Text值,这个时候IsPostBack为true,你可以判断是否要Cancel。假如回传的label2的Text和label1的Text值不同或者转换器转换到的结果不匹配那可能会出现死循环或者其他错误 /// public bool IsPostBack { get { return current.Count == 2 && current.ElementAt(1) == this && current.Peek() == this; } } bool isSourceToTarget = false; /// /// 执行数据传递 /// public virtual void SourceToTarget() { isSourceToTarget = true; object value = null; current.Push(this); try { if (Source == null || !Source.IsAlive) { if (Owner.HasProperty(TargetPropertyName)) { Owner.ClearLocalValue(TargetPropertyName); } else { var type = GetSourcePropertyType(); Owner.SetPropretyValue(TargetPropertyName, type.IsValueType ? Activator.CreateInstance(type) : null); } return; } /*var SourcePropertyNames = SourcePropertyName.Split('.'); if (SourcePropertyNames.Length > 1) { value = Source.Target; for (int i = 0; i < SourcePropertyNames.Length; i++) { value = value.GetPropretyValue(SourcePropertyNames[i]); } } else { value = Source.Target.GetPropretyValue(SourcePropertyName); }*/ value = GetPropertySource(SourcePropertyName, Source.Target); if (value != null) { value = value.GetPropretyValue(sourcePropertyNames.LastOrDefault()); } if (Convert != null) { value = Convert(value); } if (!cancel && !Owner.SetValue(value, TargetPropertyName)) { //Owner.Type.GetProperty(TargetPropertyName).FastSetValue(Owner, value); Owner.SetValue(TargetPropertyName, value); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"绑定数据执行数据传递时出错:Source:{Source.Target},Property:{SourcePropertyName} Target:{Owner},Property:{TargetPropertyName}----{e}"); if (SourceToTargetError != null) { SourceToTargetError(this, value, e); } else { throw new Exception($"绑定数据执行数据传递时出错:Source:{Source.Target},Property:{SourcePropertyName} Target:{Owner},Property:{TargetPropertyName}", e); } } finally { cancel = false; current.Pop(); isSourceToTarget = false; } } /// /// 执行数据传递 /// public virtual void TargetToSource() { if (!isSourceToTarget) { if (Source == null || !Source.IsAlive) { return; } current.Push(this); object nv = null; try { //if (Owner.HasProperty(TargetPropertyName)) //{ // nv = Owner.GetValue(TargetPropertyName); //} //else //{ // nv = Owner.Type.GetProperty(TargetPropertyName).FastGetValue(Owner); //} nv = Owner.GetPropretyValue(TargetPropertyName); if (ConvertBack != null) { nv = ConvertBack(nv); } var b = Source.Target as CpfObject; if (!cancel) { if (b != null) { if (!b.SetValue(nv, SourcePropertyName)) { /*var SourcePropertyNames = sourcePropertyNames; if (SourcePropertyNames.Length == 1) { b.SetValue(SourcePropertyName, nv); }*/ /*var Target = b; for (int i = 0; i < SourcePropertyNames.Length-1; i++) { Target = Target.GetPropretyValue(SourcePropertyNames[i]) as CpfObject; }*/ var SourcePropertyNames = sourcePropertyNames; var Target = GetPropertySource(SourcePropertyName, b); if (Target != null) { Target.SetValue(SourcePropertyNames.LastOrDefault(), nv); } //b.Type.GetProperty(SourcePropertyName).FastSetValue(b, nv); } } else { //var t = Source.Target.GetType(); //var p = t.GetProperty(SourcePropertyName); //if (p == null) //{ // throw new Exception("未找到属性:" + SourcePropertyName); //} //p.FastSetValue(Source.Target, nv); Source.Target.SetValue(SourcePropertyName, nv); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"绑定数据执行数据传递时出错:Source:{Source.Target},Property:{SourcePropertyName} Target:{Owner},Property:{TargetPropertyName}----{e}"); if (TargetToSourceError != null) { TargetToSourceError(this, nv, e); } else { throw new Exception($"绑定数据执行数据传递时出错:Source:{Source.Target},Property:{SourcePropertyName} Target:{Owner},Property:{TargetPropertyName}", e); } } finally { cancel = false; current.Pop(); } } } Type sourcePropertyType; public Type GetSourcePropertyType() { if (sourcePropertyType == null) { var b = Source.Target as CpfObject; if (b != null) { sourcePropertyType = b.GetPropertyMetadata(SourcePropertyName).PropertyType; } else { var t = Source.Target.GetType(); var p = t.GetProperty(SourcePropertyName); if (p == null) { if (t.IsValueType) { throw new Exception(t + "未找到属性:" + SourcePropertyName + " ---- 结构体作为数据源只能只读,不能将值传递回去"); } else { throw new Exception(t + "未找到属性:" + SourcePropertyName); } } sourcePropertyType = p.PropertyType; } } return sourcePropertyType; } Type targetPropertyType; public Type GetTargetPropertyType() { if (targetPropertyType == null) { var t = Owner.GetType(); targetPropertyType = t.GetProperty(TargetPropertyName).PropertyType; } return targetPropertyType; } void PropertyChanged(object sender, PropertyChangedEventArgs e) { var Temp_SourcePropertyName = sourcePropertyNames.LastOrDefault(); if (Temp_SourcePropertyName == e.PropertyName) { //CPFObject s = sender as CPFObject; //object value; //if (s == null) //{ // var p = sender.GetType().GetProperty(e.PropertyName); // value = p.FastGetValue(sender); //} //else //{ // value = s.GetValue(e.PropertyName); //} //if (Convert != null) //{ // value = Convert(value); //} //Owner.SetValue(value, TargetPropertyName); if (BindingMode == BindingMode.OneWay || BindingMode == BindingMode.TwoWay) { SourceToTarget(); } } } internal object GetPropertySource(string SourcePropertyName, object Source) { try { var SourcePropertyNames = sourcePropertyNames; if (SourcePropertyNames.Length == 1) { return Source; } var Target = Source; for (int i = 0; i < SourcePropertyNames.Length - 1; i++) { var Temp_Target = Target.GetPropretyValue(SourcePropertyNames[i]) as CpfObject; if (Temp_Target == null) { return null; } Target = Temp_Target; } return Target; } catch (Exception ex) { throw new Exception($"错误:{ex}"); } } //CpfObject SourceProperty = null; private void Target_PropertyChanged(object sender, PropertyChangedEventArgs e) { //重新绑定 if (BindingMode == BindingMode.TwoWay || BindingMode == BindingMode.OneWay || BindingMode == BindingMode.OneTime) { var SourcePropertyNames = sourcePropertyNames; var Temp_Target = GetPropertySource(SourcePropertyName, Source.Target); var data = (Temp_Target as CpfObject)?.GetValue(SourcePropertyNames.LastOrDefault()); Owner.SetPropretyValue(TargetPropertyName, data); } RegisterPropertyChanged(sender as INotifyPropertyChanged); } internal void RegisterPropertyChanged(INotifyPropertyChanged notify) { //if (owner == null) //{ // throw new Exception("错误"); //} var SourcePropertyNames = sourcePropertyNames; if (SourcePropertyNames.Length == 1) { RegisterPropertyChanged(notify, PropertyChanged); return; } var Target = Source.Target; RegisterPropertyChanged(Target as CpfObject, Target_PropertyChanged); for (int i = 0; i < SourcePropertyNames.Length - 1; i++) { var Temp_Target = Target.GetPropretyValue(SourcePropertyNames[i]) as CpfObject; if (Temp_Target == null) { return; } RegisterPropertyChanged(Temp_Target, Target_PropertyChanged); Target = Temp_Target; } RegisterPropertyChanged(Target as INotifyPropertyChanged, PropertyChanged); } internal void CancellationPropertyChanged(INotifyPropertyChanged notify) { CancellationPropertyChanged(notify, PropertyChanged); } /// /// 绑定的UIElement层次,0是自己,1是Parent,2是Parent.Parent.... /// public byte? SourceElementLayer { get; internal set; } #region IDisposable Support private bool disposedValue = false; // 要检测冗余调用 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 } UnBind(); // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 disposedValue = true; } } // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。 ~Binding() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose(false); } // 添加此代码以正确实现可处置模式。 void IDisposable.Dispose() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose(true); // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。 GC.SuppressFinalize(this); } #endregion } /// /// This enum describes how the data flows through a given Binding /// public enum BindingMode : byte { /// Data flows from source to target and vice-versa TwoWay, /// Data flows from source to target, source changes cause data flow OneWay, /// Data flows from source to target once, source changes are ignored 数据从源流到目标一次, 源更改将被忽略 OneTime, /// Data flows from target to source, target changes cause data flow OneWayToSource } //public abstract class LambdaBinding //{ // protected Delegate Action; // protected string NotifyProperty; // protected bool IsSource; // internal protected LambdaBinding Binding; // internal protected INotifyPropertyChanged Source; //} ///// ///// Lambda方式绑定,不能使用过于复杂的表达式 ///// ///// 目标类型Owner ///// 数据源类型 //public class Binding : LambdaBinding where T : CpfObject where S : INotifyPropertyChanged //{ // /// // /// 数据源是DataContext,Lambda方式绑定,不能使用过于复杂的表达式 // /// // /// // /// // public static Binding ToTarget(Action action) // { // PropertyInfo[] propertyInfos = action.GetMethodInfo().ResolveImpProperties(1); // return new Binding { Action = action, NotifyProperty = propertyInfos[0].Name, IsSource = true }; // } // /// // /// 数据源是DataContext,数据往DataContext传递,Lambda方式绑定,不能使用过于复杂的表达式 // /// // /// // /// // public static Binding ToSource(Action action) // { // PropertyInfo[] propertyInfos = action.GetMethodInfo().ResolveImpProperties(1); // return new Binding { Action = action, NotifyProperty = propertyInfos[0].Name }; // } // /// // /// Lambda方式绑定,不能使用过于复杂的表达式 // /// // /// // /// // /// // public static Binding ToTarget(S source, Action action) // { // PropertyInfo[] propertyInfos = action.GetMethodInfo().ResolveImpProperties(1); // return new Binding { Action = action, NotifyProperty = propertyInfos[0].Name, IsSource = true, Source = source }; // } // /// // /// Lambda方式绑定,不能使用过于复杂的表达式 // /// // /// // /// // /// // public static Binding ToSource(S source, Action action) // { // PropertyInfo[] propertyInfos = action.GetMethodInfo().ResolveImpProperties(1); // return new Binding { Action = action, NotifyProperty = propertyInfos[0].Name, Source = source }; // } //} public static class BindHelper { //public static Binding ToSource(this Binding binding, Action action) where T : CpfObject where S : INotifyPropertyChanged //{ // var b = Binding.ToSource(action); // b.Binding = binding; // b.Source = binding.Source; // return b; //} //public static Binding ToTarget(this Binding binding, Action action) where T : CpfObject where S : INotifyPropertyChanged //{ // var b = Binding.ToTarget(action); // b.Binding = binding; // b.Source = binding.Source; // return b; //} //public static T Bind(this T obj, S source, Expression> action, Expression> action1, BindingMode bindingMode) //{ // CpfObject target=null; // CpfObject s = null; // target.Bind(s, a => a.Attacheds, a => a.Type.Name, BindingMode.OneWay); // //PropertyInfo[] propertyInfos = action.Method.ResolveImpProperties(1); // //Expression> func = Expression.Lambda(; // return obj; //} //public static T Bind(this T obj, Expression> action, Expression> action1, BindingMode bindingMode) where T:CpfObject //{ // CpfObject target=null; // target.Bind(a => a.Attacheds, a => a.Type.Name, BindingMode.OneWay); // return obj; //} //public static T Trigger(this T obj, Expression> action, Relation relation, params (string, object)[] ps) where T : CpfObject //{ // return obj; //} /// /// 设置附加属性 /// /// /// /// /// /// /// public static T Attached(this T obj, Attached attached, V value) where T : CpfObject { attached(obj, value); return obj; } static bool IsCpfObjectGet(MethodBase source) { var declaringType = source.DeclaringType; if (typeof(CpfObject).IsAssignableFrom(declaringType)) { byte[] ILdata = source.GetMethodBody().GetILAsByteArray(); var reader = new BytesReader(ILdata); while (reader.ReadOpCode(out var opCode)) { switch (opCode.OperandType) { case OperandType.InlineMethod: if (reader.ReadInt32(out var token)) { var b = source.Module.ResolveMethod(token); if (b.Name == nameof(CpfObject.GetValue)) return true; } break; default: reader.Skip(GetOperandSize(opCode.OperandType)); break; } } } return false; } static bool FindPropertyInfo(this MethodBase methodBase, out PropertyInfo value) { value = null; foreach (var propertyInfo in methodBase.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public)) { if (propertyInfo.GetGetMethod().MetadataToken == methodBase.MetadataToken) { value = propertyInfo; break; } } return value != null; } static PropertyInfo[] ResolveImpProperties(this MethodBase source, int deep = 1) { List tp = new List(); List tm = new List(); MethodBody methodBody = source.GetMethodBody(); byte[] ILdata = methodBody.GetILAsByteArray(); var reader = new BytesReader(ILdata); Type currentType = null; void readMethod() { if (reader.ReadInt32(out var token)) { var b = source.Module.ResolveMethod(token); if (IsCpfObjectGet(b) && b.FindPropertyInfo(out var propertyInfo)) tp.Add(propertyInfo); } } //void readType() //{ // if (reader.ReadInt32(out var token)) // currentType = source.Module.ResolveType(token); //} while (reader.ReadOpCode(out var opCode)) { switch (opCode.OperandType) { case OperandType.InlineMethod: readMethod(); break; default: reader.Skip(GetOperandSize(opCode.OperandType)); break; } } if (deep - 1 > 0) tm.ForEach(x => tp.AddRange(ResolveImpProperties(x, deep - 1))); return tp.ToArray(); } static int GetOperandSize(OperandType operandType) { switch (operandType) { case OperandType.InlineBrTarget: return 4; case OperandType.InlineField: return 4; case OperandType.InlineI: return 4; case OperandType.InlineI8: return 8; case OperandType.InlineMethod: return 4; case OperandType.InlineR: return 8; case OperandType.InlineSig: return 4; case OperandType.InlineString: return 4; case OperandType.InlineSwitch: return 4; case OperandType.InlineTok: return 4; case OperandType.InlineType: return 4; case OperandType.InlineVar: return 2; case OperandType.ShortInlineBrTarget: return 1; case OperandType.ShortInlineI: return 1; case OperandType.ShortInlineR: return 4; case OperandType.ShortInlineVar: return 1; default: return 0; } } } class BytesReader { public byte[] Data; public int Index = 0; public static Dictionary OpCodeList = new Dictionary(); static BytesReader() { foreach (var opcodeFI in typeof(OpCodes).GetFields()) { var opCodeObj = opcodeFI.GetValue(null); if (opCodeObj != null) { var opCode = (OpCode)opCodeObj; OpCodeList[opCode.Value] = opCode; } } } public BytesReader(byte[] data) { Data = data; } public bool Skip(int size) { if (Index + size <= Data.Length) { Index += size; return true; } return false; } public bool ReadBytes(int size, out byte[] value) { value = null; if (Index + size <= Data.Length) { value = new byte[size]; Buffer.BlockCopy(Data, Index, value, 0, value.Length); Index += size; return true; } return false; } public bool ReadValue(out T value) where T : struct { value = default; #if NET40 int len = Marshal.SizeOf(typeof(T)); #else int len = Marshal.SizeOf(); #endif if (ReadBytes(len, out var data)) { IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.Copy(data, 0, ptr, len); #if NET40 value = (T)Marshal.PtrToStructure(ptr, typeof(T)); #else value = Marshal.PtrToStructure(ptr); #endif Marshal.FreeHGlobal(ptr); return true; } return false; } public bool ReadInt32(out Int32 value) { value = default; if (ReadBytes(4, out var data)) { value = BitConverter.ToInt32(data, 0); return true; } return false; } public bool ReadInt16(out Int16 value) { value = default; if (ReadBytes(2, out var data)) { value = BitConverter.ToInt16(data, 0); return true; } return false; } public bool ReadByte(out byte value) { value = default; if (ReadBytes(1, out var data)) { value = data[0]; return true; } return false; } public bool ReadOpCode(out OpCode value) { value = default; if (ReadByte(out var HByte)) { short key = HByte; if (key != 0xFE || (Skip(-1) && ReadInt16(out key))) { //key = HByte; return OpCodeList.TryGetValue(key, out value); } } return false; } } }