📄 binding.cs
字号:
/** Copyright (c) 2006, All-In-One Creations, Ltd.* All rights reserved.* * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:* * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.* * Neither the name of All-In-One Creations, Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.**//** * Project: emergetk: stateful web framework for the masses * File name: Binding.cs * Description: Represents a binding relationship between two IDataBindables. * * Author: Ben Joldersma * */using System;using System.Collections.Generic;using System.Text;using System.Reflection;using System.Text.RegularExpressions;namespace EmergeTk.Model{ public delegate void NotifyPropertyChanged(); public class Binding { static Regex widgetRegEx = new Regex(@"\$(?<widget>\w+)\.?(?<property>#?\w+)?", RegexOptions.Compiled); private IDataBindable destination; public IDataBindable Destination { get { return destination; } set { destination = value; } } private IDataBindable source; public IDataBindable Source { get { return source; } set { source = value; } } private string destinationProperty; public string DestinationProperty { get { return destinationProperty; } set { destinationProperty = value; } } private string sourceProperty; public string SourceProperty { get { return sourceProperty; } set { sourceProperty = value; } } private PropertyInfo pInfo; private Type fieldType; private string sourcePropertySetValue; private void DestinationChangedHandler() { object newDest = PropertyConverter.Convert(pInfo.GetValue(destination, null), fieldType); if (! newDest.Equals(source[sourcePropertySetValue])) // prevent infinite looping. { source[sourcePropertySetValue] = newDest; } } private void SourceChangedHandler() { UpdateDestination(); } public void UpdateDestination() { if (fieldRequiresFormatting) { List<object> values = new List<object>(); foreach (string f in fields) { string valString = string.Empty; if (f.StartsWith("$")) { //syntax: {$textbox1.Text} Match m = widgetRegEx.Match(f); if (m.Success) { Widget w = Context.Current.Find(m.Groups["widget"].Value); if (m.Groups["property"].Success) { object val = w[m.Groups["property"].Value]; if (val != null) valString = val.ToString(); else valString = string.Empty; } else { if (w is IDataBindable && w[(w as IDataBindable).DefaultProperty] != null) { valString = w[(w as IDataBindable).DefaultProperty].ToString(); } else { valString = w.id; } } } } else if (f == "ObjectId" && source != null) valString = source.ObjectId.ToString(); else if (source != null && source[f] != null) { if (source[f] is DateTime) valString = ((DateTime)source[f]).ToShortDateString(); else valString = source[f].ToString(); } values.Add(valString); } bool doEval = sourceProperty.StartsWith("="); string value = string.Format(sourceProperty, values.ToArray()); if (doEval) { object result = Util.JsEval(value.TrimStart('=')); if (result != null) value = result.ToString(); else value = string.Empty; } string oldString = pInfo.GetValue(destination, null) as string; if( oldString != value ) pInfo.SetValue(destination, value, null); } else { //when updating the destination, I think it's okay to supress exceptions and just populate with default values. //we obviously shouldn't ever be populating the database with bullshit data, but there is high visibility when //going the other direction. try { object newValue = PropertyConverter.Convert(source[sourceProperty], pInfo.PropertyType); object oldValue = pInfo.GetValue(destination, null); if ( newValue == null || ! newValue.Equals(oldValue)) pInfo.SetValue(destination, newValue, null); } catch (Exception e) { Debug.Trace("Eror {0} during databind.", e.Message); } } } public NotifyPropertyChanged OnDestinationChanged, OnSourceChanged; private List<string> fields; public List<string> Fields { get { return fields; } set { fields = value; source.Unbind(this); source.Bind(this); } } bool fieldRequiresFormatting = false; public Binding(IDataBindable destination, string property, IDataBindable source, string field) { this.destination = destination; this.destinationProperty = property; this.source = source; this.sourceProperty = field; OnSourceChanged = new NotifyPropertyChanged(SourceChangedHandler); if (field.Contains("{")) { fieldRequiresFormatting = true; fields = new List<string>(); //parse for formatted string. Regex r = new Regex(@"\{(?<Name>\S+?)\}", RegexOptions.Compiled); this.sourceProperty = r.Replace(field, new MatchEvaluator(delegate(Match m) { fields.Add(m.Groups[1].Value); return "{" + (fields.Count - 1).ToString() + "}"; })); if (fields.Count > 0) { foreach (string f in fields) { if (f.StartsWith("$")) { Match m = widgetRegEx.Match(f); if (m.Success) { Widget s = Context.Current.Find(m.Groups["widget"].Value); string propertyName = null; if( m.Groups["property"].Success ) { propertyName = m.Groups["property"].Value; } else if ( s is IDataBindable ) { propertyName = (s as IDataBindable).DefaultProperty; } if( propertyName != null ) s.BindProperty(propertyName, OnSourceChanged); } } } } } else { if (destination is IDataBindable) { //do not allow two way binding on formatted bindings. fieldType = source.GetFieldTypeFromName(field); OnDestinationChanged = new NotifyPropertyChanged(DestinationChangedHandler); sourcePropertySetValue = SourceProperty; } } try { pInfo = destination.GetType().GetProperty(property); } catch (System.Reflection.AmbiguousMatchException e) { pInfo = destination.GetType().GetProperty(property, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public ); } if( source != null ) source.Bind(this); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -