예제 #1
1
        public static void SetBindingObject(FrameworkElement obj, BindingMode mode, object source, DependencyProperty dp, string propertyName)
        {
            Type propertyType = source.GetType().GetProperty(propertyName).PropertyType;
            PropertyInfo info = source.GetType().GetProperty("RangeList");
            FANumberRangeRule rangeRule = null;
            if (info != null)
            {
                object value = info.GetValue(source, null);
                if (value != null)
                {
                    FALibrary.Utility.SerializableDictionary<string, FARange> dic =
                        (FALibrary.Utility.SerializableDictionary<string, FARange>)value;
                    if (dic.ContainsKey(propertyName))
                    {
                        rangeRule = new FANumberRangeRule(propertyType);
                        rangeRule.Range = dic[propertyName];
                        obj.Tag = rangeRule;
                        obj.Style = (Style)App.Current.Resources["TextBoxErrorStyle"];
                    }
                }
            }

            Binding bd = new Binding(propertyName);
            bd.Source = source;
            bd.Mode = mode;
            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            if (rangeRule != null)
            {
                bd.NotifyOnValidationError = true;
                bd.ValidationRules.Add(rangeRule);
            }

            obj.SetBinding(dp, bd);
        }
예제 #2
0
 public XamlBindingDefinition(Control target, PerspexProperty targetProperty, PropertyPath sourcePropertyPath, BindingMode bindingMode)
 {
     this.target = target;
     this.targetProperty = targetProperty;
     this.sourcePropertyPath = sourcePropertyPath;
     this.bindingMode = bindingMode;
 }
예제 #3
0
 public BindingExpression(BindingMode mode, Binding.Parsing.Expressions.BindingPathExpression path, RedwoodProperty sourceProperty = null, RedwoodBindable source = null)
 {
     Path = path;
     Mode = mode;
     SourceProperty = sourceProperty ?? Controls.RedwoodControl.DataContextProperty;
     Source = source;
 }
 public DenomTemplateColumnDefinition(string columnName, string displayMember, string headerName, DenomColumnDataType columnDataType = DenomColumnDataType.Text, string alignment = "left", string width = "auto", bool isEditable = false, bool calculationRequired = false, string formula = "", string calculationOn = "", bool totalRequired = false, string footerText = "", bool isReadOnly = false, bool isVisible = true, bool allowDecimal = false, bool allowNegativeValue = false, bool spinnerRequired = false, string seed = "1", int decimalPlaces = 0, bool currencySymbolRequired = false, CurrencySymbolPositionType currencySymbolPosition= CurrencySymbolPositionType.Header, BindingMode bindingType= BindingMode.OneWay)
 {
     this.ColumnName = columnName;
     this.DisplayMember = displayMember;
     this.Width = width;
     this.ColumnDataType = columnDataType;
     this.Alignment = alignment;
     this.HeaderName = headerName;
     this.IsEditable = isEditable;
     this.CalculationRequired = calculationRequired;
     this.Formula = formula;
     this.CalculationOn= calculationOn;
     this.TotalRequired = totalRequired;
     this.FooterText = footerText;
     this.IsReadOnly = isReadOnly;
     this.IsVisible = isVisible;
     this.AllowDecimal = allowDecimal;
     this.AllowNegativeValue = allowNegativeValue;
     this.SpinnerRequired = spinnerRequired;
     this.Seed = seed;
     this.DecimalPlaces = decimalPlaces;
     this.CurrencySymbolRequired = currencySymbolRequired;
     this.CurrencySymbolPosition = currencySymbolPosition;
     this.BindingType = bindingType;
 }
예제 #5
0
 public XamlBindingDefinition(Control target, PerspexProperty targetProperty, PropertyPath sourcePropertyPath, BindingMode bindingMode)
 {
     _target = target;
     _targetProperty = targetProperty;
     _sourcePropertyPath = sourcePropertyPath;
     _bindingMode = bindingMode;
 }
예제 #6
0
 public static BindingExpressionBase SetBinding(this FrameworkElement target, DependencyProperty dp, object source, string path, BindingMode bindingMode)
 {
     Binding b = new Binding(path);
     b.Source = source;
     b.Mode = bindingMode;
     return BindingOperations.SetBinding(target, dp, b);
 }
예제 #7
0
        private static void BindParameter(FrameworkElement target, Parameter parameter, string elementName, string path, BindingMode bindingMode)
        {
            var element = elementName == "$this"
                ? target
                : ExtensionMethods.GetNamedElementsInScope(target).FindName(elementName);
            if (element == null)
                return;

            if(string.IsNullOrEmpty(path))
                path = ConventionManager.GetElementConvention(element.GetType()).ParameterProperty;

            var binding = new Binding(path) {
                Source = element,
                Mode = bindingMode
            };

            #if SILVERLIGHT
            var expression = (BindingExpression)BindingOperations.SetBinding(parameter, Parameter.ValueProperty, binding);

            var field = element.GetType().GetField(path + "Property", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
            if (field == null)
                return;

            ConventionManager.ApplySilverlightTriggers(element, (DependencyProperty)field.GetValue(null), x => expression);
            #else
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(parameter, Parameter.ValueProperty, binding);
            #endif
        }
예제 #8
0
파일: Binder.cs 프로젝트: li5414/uBinding
 protected Binder(IChangable source, IChangable target, BindingMode mode)
 {
     _source = source;
     _target = target;
     _sourceIsUsed = mode == BindingMode.OneWay || mode == BindingMode.TwoWay;
     _targetIsUsed = mode == BindingMode.OneWayToSource || mode == BindingMode.TwoWay;
 }
예제 #9
0
 public XamlBindingDefinition(
     string sourcePropertyPath, 
     BindingMode bindingMode)
 {
     SourcePropertyPath = sourcePropertyPath;
     BindingMode = bindingMode;
 }
 public static void SetBindingObject(FrameworkElement obj, BindingMode mode, object source, DependencyProperty dp, string propertyName)
 {
     Binding bd = new Binding(propertyName);
     bd.Source = source;
     bd.Mode = mode;
     obj.SetBinding(dp, bd);
 }
예제 #11
0
 public UnitTestSettings(BindingMode bindingMode, AssertMode assertMode, bool moduleInit, bool methodInit, bool defaultTestStub)
 {
     BindingMode = bindingMode;
     AssertMode = assertMode;
     ModuleInit = moduleInit;
     MethodInit = methodInit;
     DefaultTestStubInNewModule = defaultTestStub;
 }
예제 #12
0
 public static void BindProperty(Control control, object source, string path,
     DependencyProperty property, BindingMode mode)
 {
     var binding = new Binding(path);
     binding.Source = source;
     binding.Mode = mode;
     control.SetBinding(property, binding);
 }
예제 #13
0
 /// <summary>
 /// Initializes a new BindingInfo with a path, a source binding RelativeSourceMode, and an optional converter. 
 /// </summary>
 /// <param name="path">The path to the source member.</param>
 /// <param name="bindingMode">The binding direction.</param>
 /// <param name="relativeSourceMode">The source RelativeSourceMode.</param>
 /// <param name="converterType">An optional converter.</param>
 /// <param name="converterParameter">An optional converter parameter.</param>
 internal BindingInfo(string path, BindingMode bindingMode, RelativeSourceMode relativeSourceMode, Type converterType = null,
     object converterParameter = null)
 {
     Path = path;
     RelativeSourceMode = relativeSourceMode;
     ConverterType = converterType;
     ConverterParameter = converterParameter;
 }
예제 #14
0
 public static void BindProperty(FrameworkElement element, object source, 
     string path, DependencyProperty property, BindingMode mode)
 {
     var binding = new Binding(path);
     binding.Source = source;
     binding.Mode = mode;
     element.SetBinding(property, binding);
 }
예제 #15
0
 public DependencyWatcher(
     Dependency[] dependencies, 
     BindingMode mode,
     BindindErrorOptions errorOptions
 ) {
     _dependencies = dependencies;
     _mode = mode;
     _errorOptions = errorOptions;
 }
예제 #16
0
 public IndexerBinding(
     IAvaloniaObject source,
     AvaloniaProperty property,
     BindingMode mode)
 {
     Source = source;
     Property = property;
     Mode = mode;
 }
예제 #17
0
 /// <summary>
 /// Merges the metadata with the base metadata.
 /// </summary>
 /// <param name="baseMetadata">The base metadata to merge.</param>
 /// <param name="property">The property to which the metadata is being applied.</param>
 public virtual void Merge(
     PropertyMetadata baseMetadata, 
     AvaloniaProperty property)
 {
     if (_defaultBindingMode == BindingMode.Default)
     {
         _defaultBindingMode = baseMetadata.DefaultBindingMode;
     }
 }
예제 #18
0
 /// <summary>
 /// バインディングを追加します。
 /// </summary>
 public Binding Add(object bindableTarget, string bindingPropertyName,
                    object dataSource, string dataSourcePropertyName,
                    BindingMode mode, string format = null)
 {
     return Add(
         bindableTarget, bindingPropertyName,
         dataSource, dataSourcePropertyName,
         mode, format, null, null);
 }
예제 #19
0
파일: BindingNode.cs 프로젝트: sys27/Edge
        public BindingNode(string elementName, string path, BindingMode mode)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException(nameof(path));

            this.elementName = elementName;
            this.path = path;
            this.mode = mode;
        }
예제 #20
0
        public static BindingExpressionBase SetBinding(DependencyObject target, DependencyProperty targetProperty, DependencyObject source, DependencyProperty sourceProperty, BindingMode mode, IValueConverter converter)
        {
            Binding binding = new Binding(sourceProperty.Name);
            binding.Source = source;
            binding.Converter = converter;
            binding.Mode = mode;

            return BindingOperations.SetBinding(target, targetProperty, binding);
        }
예제 #21
0
 /// <summary/>
 public PresenterBinding(
     Type presenterType,
     Type viewType,
     BindingMode bindingMode,
     IEnumerable<IView> viewInstances)
 {
     this.presenterType = presenterType;
     this.viewType = viewType;
     this.bindingMode = bindingMode;
     this.viewInstances = viewInstances;
 }
예제 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicableBinding"/> class.
 /// </summary>
 /// <param name="elementDescription">The element description.</param>
 /// <param name="dependencyProperty">The dependency property.</param>
 /// <param name="path">The path.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="validate">Inidicates whether or not to turn on validation for the binding.</param>
 /// <param name="checkTemplate">if set to <c>true</c> [check item template].</param>
 /// <param name="converter">The value converter to apply.</param>
 public ApplicableBinding(ElementDescription elementDescription, DependencyProperty dependencyProperty, string path, 
     BindingMode mode, bool validate, bool checkTemplate, IValueConverter converter)
 {
     this.elementDescription = elementDescription;
     this.dependencyProperty = dependencyProperty;
     this.path = path;
     this.mode = mode;
     this.validate = validate;
     this.checkTemplate = checkTemplate;
     this.converter = converter;
 }
예제 #23
0
        public WaveKeyframeDataBinding( BoundProperty boundProperty, BindingMode bindingMode, float srcFrom, float srcTo, float targetFrom, float targetTo )
        {
            m_property 		= boundProperty;
            m_mode	   		= bindingMode;

            m_sourceFrom 	= srcFrom;
            m_sourceTo 		= srcTo;

            m_targetFrom	= targetFrom;
            m_targetTo		= targetTo;
        }
예제 #24
0
        public void ShouldApplyBindingToTargetAfterCreation(BindingMode mode) {
            var source = new Source { SourceName = "changed" };
            var target = new Target();

            Bind.Property(() => source.SourceName)
                .In(mode)
                .To(() => target.TargetName);

            Assert.AreEqual("changed", source.SourceName);
            Assert.AreEqual("changed", target.TargetName);
        }
예제 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InstancedBinding"/> class.
        /// </summary>
        /// <param name="subject">The subject for a two-way binding.</param>
        /// <param name="mode">The binding mode.</param>
        /// <param name="priority">The binding priority.</param>
        public InstancedBinding(
            ISubject<object> subject,
            BindingMode mode = BindingMode.OneWay,
            BindingPriority priority = BindingPriority.LocalValue)
        {
            Contract.Requires<ArgumentNullException>(subject != null);

            Mode = mode;
            Priority = priority;
            Subject = subject;
        }
예제 #26
0
        public static void SetBindingObject(FrameworkElementFactory obj, BindingMode mode, DependencyProperty dp, string propertyName)
        {
            obj.AddHandler(FrameworkElement.LoadedEvent,
                new RoutedEventHandler(
                    delegate(object sender, RoutedEventArgs e)
                    {
                        try
                        {
                            FrameworkElement fe = (FrameworkElement)sender;
                            var bindingEx = fe.GetBindingExpression(dp);
                            if (bindingEx == null) return;

                            object dataItem = bindingEx.DataItem;
                            string[] strs = fe.GetBindingExpression(dp).ParentBinding.Path.Path.Split('.');
                            bool firstSearched = false;
                            string property = "";
                            foreach (var item in strs)
                            {
                                if (firstSearched)
                                {
                                    dataItem = dataItem.GetType().GetProperty(property).GetValue(dataItem, null);
                                }
                                else
                                    firstSearched = true;

                                property = dataItem.GetType().GetProperty(item).Name;
                            }

                            SetBindingObject(fe,
                                fe.GetBindingExpression(dp).ParentBinding.Mode,
                                dataItem,
                                dp,
                                property);
                        }
                        catch
                        {
                        }
                    }));
            try
            {
                if (obj.Type == typeof(TextBox))
                    obj.SetValue(FrameworkElement.StyleProperty, App.Current.Resources["TextBoxErrorStyle"]);
            }
            catch
            {
            }

            Binding bd = new Binding(propertyName);
            bd.Mode = mode;
            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            bd.NotifyOnValidationError = true;
            obj.SetBinding(dp, bd);
        }
예제 #27
0
		/// <summary>
		/// Inicjalizuje wiązanie.
		/// </summary>
		/// <param name="source">Obiekt źródłowy.</param>
		/// <param name="sourceProperty">Ścieżka do źródła.</param>
		/// <param name="target">Obiekt docelowy.</param>
		/// <param name="targetProperty">Ścieżka do celu.</param>
		/// <param name="mode">Tryb wiązania.</param>
		/// <param name="converterType">Wymuszony typ konwertera.</param>
		/// <exception cref="ArgumentNullException">Któryś z argumentów jest nullem.</exception>
		internal Binding(object source, IPropertyPath sourceProperty, object target, IPropertyPath targetProperty, bool setTarget,
			BindingMode mode = BindingMode.OneWay, Type converterType = null)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (sourceProperty == null)
			{
				throw new ArgumentNullException("sourceProperty");
			}
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			if (targetProperty == null)
			{
				throw new ArgumentNullException("targetProperty");
			}
			this.SourcePath = sourceProperty;
			if (!this.SourcePath.Initialized)
			{
				this.SourcePath.BeginInit();
				this.SourcePath.Root = source;
				this.SourcePath.EndInit();
			}
			else
			{
				this.SourcePath.Root = source;
			}

			this.TargetPath = targetProperty;
			if (!this.TargetPath.Initialized)
			{
				this.TargetPath.BeginInit();
				this.TargetPath.Root = target;
				this.TargetPath.EndInit();
			}
			else
			{
				this.TargetPath.Root = target;
			}

			this.Mode = mode;
			this.ConverterType = converterType;
			this.SetBindings();

			if (setTarget)
			{
				this.TargetPath.Value = this.GetConvertedSource();
			}
		}
예제 #28
0
 public void AddImageColumn(string bindingName,
     string headerText,
     int widthPercent,
     BindingMode bindingMode,
     string sortOn="",Style style=null)
 {
     FrameworkElementFactory ef = new FrameworkElementFactory(typeof(Image));
     Binding binding = new Binding(bindingName);
     binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
     binding.Mode = bindingMode;
     ef.SetValue(Image.SourceProperty, binding);
     AddColumn(ef, widthPercent,headerText,sortOn,style);
 }
예제 #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Binding"/> class.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="converter">The converter.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target"/> is <c>null</c>.</exception>
        public Binding(BindingParty source, BindingParty target, BindingMode mode = BindingMode.TwoWay, IValueConverter converter = null)
        {
            Argument.IsNotNull("source", source);
            Argument.IsNotNull("target", target);

            Mode = mode;
            Converter = converter;

            _source = source;
            _target = target;

            Initialize();
        }
예제 #30
0
		public DataSourceBinding(string path, BindingMode mode = BindingMode.Default, IValueConverter converter = null, object converterParameter = null, string stringFormat = null)
		{
			if (path == null)
				throw new ArgumentNullException(nameof(path));
			if (string.IsNullOrWhiteSpace(path))
				throw new ArgumentException("path can not be an empty string", nameof(path));

			AllowChaining = true;
			Path = path;
			Converter = converter;
			ConverterParameter = converterParameter;
			Mode = mode;
			StringFormat = stringFormat;
		}
예제 #31
0
 public static T Binding <T>(this T element, string property, string propertyPath, object source, BindingMode mode) where T : DependencyObject
 {
     return(element.Binding(property,
                            new Data.Binding()
     {
         Path = propertyPath,
         Source = source,
         Mode = mode
     }
                            ));
 }
예제 #32
0
        /// <summary>
        /// Bind the combo box to ObservableList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ComboBox"></param>
        /// <param name="obj">Object to bind to</param>
        /// <param name="Field">Object field to bind</param>
        /// <param name="list">List of Observable items to display in the combo box</param>
        /// <param name="DisplayMemberPath">list item field to display</param>
        /// <param name="SelectedValuePath">list item value to return when selected</param>
        public static void BindControl <T>(this ComboBox ComboBox, Object obj, string Field, ObservableList <T> list, string DisplayMemberPath, string SelectedValuePath, BindingMode bindingMode = BindingMode.TwoWay)
        {
            ComboBox.ItemsSource       = list;
            ComboBox.DisplayMemberPath = DisplayMemberPath;
            ComboBox.SelectedValuePath = SelectedValuePath;

            //ControlsBinding.ObjFieldBinding(ComboBox, ComboBox.SelectedValueProperty, obj, Field, bindingMode);
            GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(ComboBox, ComboBox.SelectedValueProperty, obj, Field, bindingMode);
        }
예제 #33
0
 public static void BindControl(this TreeView TreeView, Object obj, string Field, BindingMode bm = BindingMode.TwoWay)
 {
     GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(TreeView, TreeView.SelectedValuePathProperty, obj, Field, bm);
 }
예제 #34
0
 internal BindingBase(object source, PropertyPath sourcePath, object target, PropertyPath targetPath, IValueConverter converter = null, object converterParameter = null, UpdateSourceTrigger updateSourceTrigger = UpdateSourceTrigger.PropertyChanged, BindingMode model = BindingMode.OneWay)
 {
     this.source         = source ?? throw new ArgumentNullException(nameof(source));
     SourcePath          = sourcePath;
     Target              = target;
     TargetPath          = targetPath ?? throw new ArgumentNullException(nameof(targetPath));
     Converter           = converter;
     ConverterParameter  = converterParameter;
     UpdateSourceTrigger = updateSourceTrigger;
     Model = model;
     sourcePath?.SetRelySource(source);
     targetPath?.SetRelySource(target);
     Validates = new Collection <IValidateValue>();
 }
예제 #35
0
 public static void ActInputValueBinding(System.Windows.Controls.Control control, DependencyProperty dependencyProperty, ActInputValue actInputValue, BindingMode BindingMode = BindingMode.TwoWay)
 {
     ObjFieldBinding(control, dependencyProperty, actInputValue, ActInputValue.Fields.Value, BindingMode);
 }
예제 #36
0
        public static void LoadAndMonitor(INotifyPropertyChanged source, string sourceProperty, Control control, DependencyProperty controlProperty = null, IValueConverter converter = null, BindingMode mode = BindingMode.Default)
        {
            var p       = controlProperty ?? GetProperty(control);
            var binding = new System.Windows.Data.Binding(sourceProperty);

            binding.Source    = source;
            binding.IsAsync   = true;
            binding.Converter = converter;
            binding.Mode      = mode;
            // Set UpdateSourceTrigger to PropertyChanged, otherwise control to object update won't trigger.
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            if (converter is Converters.PaddSettingToText)
            {
                var padValidator = new Converters.PadSettingToTextValidator();
                binding.ValidationRules.Add(padValidator);
                control.SetBinding(p, binding);
            }
            else if (converter != null)
            {
                binding.Mode = BindingMode.OneWayToSource;
                var value = source.GetType().GetProperty(sourceProperty).GetValue(source);
                var v     = converter.Convert(value, null, null, null);
                control.SetBinding(p, binding);
                control.SetValue(p, v);
            }
            else
            {
                control.SetBinding(p, binding);
            }
        }
예제 #37
0
        public static void Bind(object dataSource, string sourcePath, FrameworkElement destinationObject, DependencyProperty dp, string stringFormat, BindingMode bindingMode, IValueConverter converter)
        {
            Binding binding = new Binding
            {
                Source = dataSource,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Mode         = bindingMode,
                Path         = new PropertyPath(sourcePath),
                StringFormat = stringFormat,
                Converter    = converter
            };

            destinationObject.SetBinding(dp, binding);
        }
예제 #38
0
 public static void Bind(object dataSource, string sourcePath, FrameworkElement destinationObject, DependencyProperty dp, string stringFormat, BindingMode bindingMode)
 {
     Bind(dataSource, sourcePath, destinationObject, dp, stringFormat, bindingMode, null);
 }
        BindableProperty(string propertyName, Type returnType, Type declaringType, object defaultValue, BindingMode defaultBindingMode = BindingMode.OneWay,
                         ValidateValueDelegate validateValue = null, BindingPropertyChangedDelegate propertyChanged  = null, BindingPropertyChangingDelegate propertyChanging = null,
                         CoerceValueDelegate coerceValue     = null, BindablePropertyBindingChanging bindingChanging = null, bool isReadOnly = false, CreateDefaultValueDelegate defaultValueCreator = null)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName");
            }
            if (ReferenceEquals(returnType, null))
            {
                throw new ArgumentNullException("returnType");
            }
            if (ReferenceEquals(declaringType, null))
            {
                throw new ArgumentNullException("declaringType");
            }

            // don't use Enum.IsDefined as its redonkulously expensive for what it does
            if (defaultBindingMode != BindingMode.Default && defaultBindingMode != BindingMode.OneWay && defaultBindingMode != BindingMode.OneWayToSource && defaultBindingMode != BindingMode.TwoWay && defaultBindingMode != BindingMode.OneTime)
            {
                throw new ArgumentException("Not a valid type of BindingMode", "defaultBindingMode");
            }

            if (defaultValue == null && Nullable.GetUnderlyingType(returnType) == null && returnType.GetTypeInfo().IsValueType)
            {
                defaultValue = Activator.CreateInstance(returnType);
            }

            if (defaultValue != null && !returnType.IsInstanceOfType(defaultValue))
            {
                throw new ArgumentException("Default value did not match return type", "defaultValue");
            }

            if (defaultBindingMode == BindingMode.Default)
            {
                defaultBindingMode = BindingMode.OneWay;
            }

            PropertyName        = propertyName;
            ReturnType          = returnType;
            ReturnTypeInfo      = returnType.GetTypeInfo();
            DeclaringType       = declaringType;
            DefaultValue        = defaultValue;
            DefaultBindingMode  = defaultBindingMode;
            PropertyChanged     = propertyChanged;
            PropertyChanging    = propertyChanging;
            ValidateValue       = validateValue;
            CoerceValue         = coerceValue;
            BindingChanging     = bindingChanging;
            IsReadOnly          = isReadOnly;
            DefaultValueCreator = defaultValueCreator;
        }
 internal static BindableProperty CreateAttached(string propertyName, Type returnType, Type declaringType, object defaultValue, BindingMode defaultBindingMode, ValidateValueDelegate validateValue,
                                                 BindingPropertyChangedDelegate propertyChanged, BindingPropertyChangingDelegate propertyChanging, CoerceValueDelegate coerceValue, BindablePropertyBindingChanging bindingChanging,
                                                 bool isReadOnly, CreateDefaultValueDelegate defaultValueCreator = null)
 {
     return(new BindableProperty(propertyName, returnType, declaringType, defaultValue, defaultBindingMode, validateValue, propertyChanged, propertyChanging, coerceValue, bindingChanging, isReadOnly,
                                 defaultValueCreator));
 }
 public static BindableProperty CreateAttached(string propertyName, Type returnType, Type declaringType, object defaultValue, BindingMode defaultBindingMode = BindingMode.OneWay,
                                               ValidateValueDelegate validateValue = null, BindingPropertyChangedDelegate propertyChanged = null, BindingPropertyChangingDelegate propertyChanging = null,
                                               CoerceValueDelegate coerceValue     = null, CreateDefaultValueDelegate defaultValueCreator = null)
 {
     return(CreateAttached(propertyName, returnType, declaringType, defaultValue, defaultBindingMode, validateValue, propertyChanged, propertyChanging, coerceValue, null, false, defaultValueCreator));
 }
        internal static BindableProperty Create <TDeclarer, TPropertyType>(Expression <Func <TDeclarer, TPropertyType> > getter, TPropertyType defaultValue, BindingMode defaultBindingMode,
                                                                           ValidateValueDelegate <TPropertyType> validateValue, BindingPropertyChangedDelegate <TPropertyType> propertyChanged, BindingPropertyChangingDelegate <TPropertyType> propertyChanging,
                                                                           CoerceValueDelegate <TPropertyType> coerceValue, BindablePropertyBindingChanging bindingChanging, bool isReadOnly = false,
                                                                           CreateDefaultValueDelegate <TDeclarer, TPropertyType> defaultValueCreator = null) where TDeclarer : BindableObject
        {
            if (getter == null)
            {
                throw new ArgumentNullException("getter");
            }

            Expression expr = getter.Body;

            var unary = expr as UnaryExpression;

            if (unary != null)
            {
                expr = unary.Operand;
            }

            var member = expr as MemberExpression;

            if (member == null)
            {
                throw new ArgumentException("getter must be a MemberExpression", "getter");
            }

            var property = (PropertyInfo)member.Member;

            ValidateValueDelegate           untypedValidateValue           = null;
            BindingPropertyChangedDelegate  untypedBindingPropertyChanged  = null;
            BindingPropertyChangingDelegate untypedBindingPropertyChanging = null;
            CoerceValueDelegate             untypedCoerceValue             = null;
            CreateDefaultValueDelegate      untypedDefaultValueCreator     = null;

            if (validateValue != null)
            {
                untypedValidateValue = (bindable, value) => validateValue(bindable, (TPropertyType)value);
            }
            if (propertyChanged != null)
            {
                untypedBindingPropertyChanged = (bindable, oldValue, newValue) => propertyChanged(bindable, (TPropertyType)oldValue, (TPropertyType)newValue);
            }
            if (propertyChanging != null)
            {
                untypedBindingPropertyChanging = (bindable, oldValue, newValue) => propertyChanging(bindable, (TPropertyType)oldValue, (TPropertyType)newValue);
            }
            if (coerceValue != null)
            {
                untypedCoerceValue = (bindable, value) => coerceValue(bindable, (TPropertyType)value);
            }
            if (defaultValueCreator != null)
            {
                untypedDefaultValueCreator = o => defaultValueCreator((TDeclarer)o);
            }

            return(new BindableProperty(property.Name, property.PropertyType, typeof(TDeclarer), defaultValue, defaultBindingMode, untypedValidateValue, untypedBindingPropertyChanged,
                                        untypedBindingPropertyChanging, untypedCoerceValue, bindingChanging, isReadOnly, untypedDefaultValueCreator));
        }
 public static BindablePropertyKey CreateReadOnly(string propertyName, Type returnType, Type declaringType, object defaultValue, BindingMode defaultBindingMode = BindingMode.OneWayToSource,
                                                  ValidateValueDelegate validateValue = null, BindingPropertyChangedDelegate propertyChanged = null, BindingPropertyChangingDelegate propertyChanging = null,
                                                  CoerceValueDelegate coerceValue     = null, CreateDefaultValueDelegate defaultValueCreator = null)
 {
     return
         (new BindablePropertyKey(new BindableProperty(propertyName, returnType, declaringType, defaultValue, defaultBindingMode, validateValue, propertyChanged, propertyChanging, coerceValue,
                                                       isReadOnly: true, defaultValueCreator: defaultValueCreator)));
 }
        private bool HandleKeyboardKeyDownEvent(KeyboardKeyDownEvent keyboardKeyDownEvent)
        {
            if (bindingMode == BindingMode.primary || bindingMode == BindingMode.secondary)
            {
                BindingControl other1 = BindingControl.none;
                BindingControl other2 = BindingControl.none;
                switch (keyboardKeyDownEvent._key)
                {
                case Keys.D0:
                case Keys.D1:
                case Keys.D2:
                case Keys.D3:
                case Keys.D4:
                case Keys.D5:
                case Keys.D6:
                case Keys.D7:
                case Keys.D8:
                case Keys.D9:

                case Keys.A:
                case Keys.B:
                case Keys.C:
                case Keys.D:
                case Keys.E:
                case Keys.F:
                case Keys.G:
                case Keys.H:
                case Keys.I:
                case Keys.J:
                case Keys.K:
                case Keys.L:
                case Keys.M:
                case Keys.N:
                case Keys.O:
                case Keys.P:
                case Keys.Q:
                case Keys.R:
                case Keys.S:
                case Keys.T:
                case Keys.U:
                case Keys.V:
                case Keys.W:
                case Keys.X:
                case Keys.Y:
                case Keys.Z:

                case Keys.Up:
                case Keys.Down:
                case Keys.Left:
                case Keys.Right:

                case Keys.OemOpenBrackets:
                case Keys.OemCloseBrackets:
                case Keys.OemSemicolon:
                case Keys.OemQuotes:
                case Keys.OemComma:
                case Keys.OemPeriod:
                case Keys.OemQuestion:
                case Keys.OemBackslash:
                case Keys.OemMinus:
                case Keys.OemPlus:
                case Keys.Space:
                    switch (bindingControl)
                    {
                    case BindingControl.rotate_counter_clockwise:
                        other1 = BindingControl.rotate_clockwise;
                        other2 = BindingControl.super_shield;
                        break;

                    case BindingControl.rotate_clockwise:
                        other1 = BindingControl.rotate_counter_clockwise;
                        other2 = BindingControl.super_shield;
                        break;

                    case BindingControl.super_shield:
                        other1 = BindingControl.rotate_counter_clockwise;
                        other2 = BindingControl.rotate_clockwise;
                        break;
                    }
                    // if 'other1' is assigned to the value the user attempts to bind to 'bindingControl' then the two will swap values
                    if (CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{other1}")) == (int)keyboardKeyDownEvent._key)
                    {
                        CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{other1}")) = CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{bindingControl}"));
                    }
                    // if 'other2' is assigned to the value the user attempts to bind to 'bindingControl' then the two will swap values
                    if (CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{other2}")) == (int)keyboardKeyDownEvent._key)
                    {
                        CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{other2}")) = CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{bindingControl}"));
                    }
                    CVars.Get <int>(string.Format($"input_keyboard_{bindingMode}_{bindingControl}")) = (int)keyboardKeyDownEvent._key;
                    CVars.Save();
                    UpdateButtonBindingsForKeyboard();
                    bindingMode    = BindingMode.none;
                    bindingControl = BindingControl.none;
                    //((Button)_root.FindWidgetByID("primary_rotate_rotate_counter_clockwise")).isSelected = true;
                    _root.AutoControlModeSwitching = true;
                    return(true);

                default:
                    break;
                }
            }
            else
            {
                if (keyboardKeyDownEvent._key == Keys.Escape)
                {
                    if (isOnLeftSide)
                    {
                        ChangeState(new UIMenuGameState(GameManager, SharedState));
                    }
                    if (!isOnLeftSide)
                    {
                        switch (leftSideIndex)
                        {
                        case 0:
                            ((Button)_root.FindWidgetByID("Display")).isSelected = true;
                            isOnLeftSide = true;
                            // Deslection of button/slider should be handled in the button/slider class
                            ((Panel)_root.FindWidgetByID("display_options_menu_right_panel")).Hidden = true;
                            break;

                        case 1:
                            ((Button)_root.FindWidgetByID("Controls")).isSelected = true;
                            isOnLeftSide = true;
                            // Deslection of button/slider should be handled in the button/slider class
                            ((Panel)_root.FindWidgetByID("controls_options_menu_right_panel")).Hidden = true;
                            break;

                        case 2:
                            ((Button)_root.FindWidgetByID("GameSettings")).isSelected = true;
                            isOnLeftSide = true;
                            // Deslection of button/slider should be handled in the button/slider class
                            ((Panel)_root.FindWidgetByID("game_options_menu_right_panel")).Hidden = true;
                            break;
                        }
                    }
                    return(true);
                }
            }

            return(false);
        }
예제 #45
0
 public Binding WithMode(BindingMode mode)
 {
     this.Mode = mode;
     return(this);
 }
        public bool Handle(IEvent evt)
        {
            if (evt is EnterMouseUIModeEvent)
            {
                UpdateButtonBindingsForKeyboard();
            }
            if (evt is EnterGamePadUIModeEvent)
            {
                UpdateButtonBindingsForGamePad(((EnterGamePadUIModeEvent)evt).PlayerIndex);
            }
            if (evt is GamePadUIModeOperatorChangedEvent)
            {
                UpdateButtonBindingsForGamePad(((GamePadUIModeOperatorChangedEvent)evt).PlayerIndex);
            }

            GamePadButtonDownEvent gpbde = evt as GamePadButtonDownEvent;

            if (gpbde != null)
            {
                if (bindingMode == BindingMode.none && gpbde._pressedButton == Buttons.B)
                {
                    _root.FindSelectedWidget().isSelected = false;
                    if (isOnLeftSide == true)
                    {
                        ChangeState(new UIMenuGameState(GameManager, SharedState));
                        return(true);
                    }
                    if (isOnLeftSide == false)
                    {
                        foreach (DropDownPanel ddp in _root.FindWidgetsByClass("DropDown"))
                        {
                            ddp.ShowDropDown = false;
                            ddp.isSelected   = false;
                        }

                        switch (leftSideIndex)
                        {
                        case 0:
                            ((Panel)_root.FindWidgetByID("display_options_menu_right_panel")).Hidden = true;
                            ((Button)_root.FindWidgetByID("Display")).isSelected = true;
                            isOnLeftSide = true;
                            break;

                        case 1:
                            ((Panel)_root.FindWidgetByID("controls_options_menu_right_panel")).Hidden = true;
                            ((Button)_root.FindWidgetByID("Controls")).isSelected = true;
                            isOnLeftSide = true;
                            break;

                        case 2:
                            ((Panel)_root.FindWidgetByID("game_options_menu_right_panel")).Hidden = true;
                            ((Button)_root.FindWidgetByID("GameSettings")).isSelected             = true;
                            isOnLeftSide = true;
                            break;
                        }
                    }
                }
                if (bindingMode == BindingMode.gamepad)
                {
                    BindingControl other1 = BindingControl.none;
                    BindingControl other2 = BindingControl.none;
                    switch (gpbde._pressedButton)
                    {
                    case Buttons.A:
                    case Buttons.B:
                    case Buttons.X:
                    case Buttons.Y:
                    case Buttons.LeftTrigger:
                    case Buttons.LeftShoulder:
                    case Buttons.LeftStick:
                    case Buttons.RightTrigger:
                    case Buttons.RightShoulder:
                    case Buttons.RightStick:
                    case Buttons.DPadUp:
                    case Buttons.DPadDown:
                    case Buttons.DPadLeft:
                    case Buttons.DPadRight:
                    case Buttons.LeftThumbstickUp:
                    case Buttons.LeftThumbstickDown:
                    case Buttons.LeftThumbstickLeft:
                    case Buttons.LeftThumbstickRight:
                    case Buttons.RightThumbstickUp:
                    case Buttons.RightThumbstickDown:
                    case Buttons.RightThumbstickLeft:
                    case Buttons.RightThumbstickRight:
                        switch (bindingControl)
                        {
                        case BindingControl.rotate_counter_clockwise:
                            other1 = BindingControl.rotate_clockwise;
                            other2 = BindingControl.super_shield;
                            break;

                        case BindingControl.rotate_clockwise:
                            other1 = BindingControl.rotate_counter_clockwise;
                            other2 = BindingControl.super_shield;
                            break;

                        case BindingControl.super_shield:
                            other1 = BindingControl.rotate_counter_clockwise;
                            other2 = BindingControl.rotate_clockwise;
                            break;
                        }
                        // if 'other1' is assigned to the value the user attempts to bind to 'bindingControl' then the two will swap values
                        if (CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{other1}")) == (int)gpbde._pressedButton)
                        {
                            CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{other1}")) = CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{bindingControl}"));
                        }
                        // if 'other2' is assigned to the value the user attempts to bind to 'bindingControl' then the two will swap values
                        if (CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{other2}")) == (int)gpbde._pressedButton)
                        {
                            CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{other2}")) = CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{bindingControl}"));
                        }
                        CVars.Get <int>(string.Format($"input_controller_{(int)gpbde._playerIndex}_{bindingControl}")) = (int)gpbde._pressedButton;
                        break;

                    default:
                        return(true);
                    }
                    CVars.Save();
                    UpdateButtonBindingsForGamePad(gpbde._playerIndex);
                    ((Button)_root.FindWidgetByID(string.Format($"{bindingControl}"))).isSelected = true;
                    bindingControl = BindingControl.none;
                    _root.AutoControlModeSwitching = true;
                    return(true);
                }
            }

            KeyboardKeyDownEvent kbkde = evt as KeyboardKeyDownEvent;

            if (kbkde != null)
            {
                return(HandleKeyboardKeyDownEvent(kbkde));
            }

            // Listen for the 3 types of button settings pressed
            // Consider buttonSelectedEvent and buttonDeselectedEvent to allow showing of right side
            DisplaySettingsButtonPressedEvent displaySBPE = evt as DisplaySettingsButtonPressedEvent;

            if (displaySBPE != null)
            {
                isOnLeftSide  = false;
                leftSideIndex = 0;
                Console.WriteLine("displaySBPE");

                //_root.FindSelectedWidget().isSelected = false;
                ((Button)_root.FindWidgetByID("Display")).isSelected = false;
                ((DropDownPanel)_root.FindWidgetByID("Screen_Size_Settings_Dropdown")).isSelected = true;

                ((Panel)_root.FindWidgetByID("controls_options_menu_right_panel")).Hidden = true;
                ((Panel)_root.FindWidgetByID("game_options_menu_right_panel")).Hidden     = true;
                ((Panel)_root.FindWidgetByID("display_options_menu_right_panel")).Hidden  = false;
            }
            ControlsSettingsButtonPressedEvent controlsSBPE = evt as ControlsSettingsButtonPressedEvent;

            if (controlsSBPE != null)
            {
                isOnLeftSide  = false;
                leftSideIndex = 1;
                Console.WriteLine("controlSBPE");

                //_root.FindSelectedWidget().isSelected = false;
                ((Button)_root.FindWidgetByID("Controls")).isSelected = false;
                ((Button)_root.FindWidgetByID("primary_rotate_counter_clockwise")).isSelected = true;

                ((Panel)_root.FindWidgetByID("controls_options_menu_right_panel")).Hidden = false;
                ((Panel)_root.FindWidgetByID("game_options_menu_right_panel")).Hidden     = true;
                ((Panel)_root.FindWidgetByID("display_options_menu_right_panel")).Hidden  = true;
            }
            GameSettingsButtonPressedEvent gameSBPE = evt as GameSettingsButtonPressedEvent;

            if (gameSBPE != null)
            {
                isOnLeftSide  = false;
                leftSideIndex = 2;
                Console.WriteLine("gameSBPE");

                //_root.FindSelectedWidget().isSelected = false;
                ((Button)_root.FindWidgetByID("GameSettings")).isSelected          = false;
                ((DropDownPanel)_root.FindWidgetByID("Speed_Dropdown")).isSelected = true;

                ((Panel)_root.FindWidgetByID("controls_options_menu_right_panel")).Hidden = true;
                ((Panel)_root.FindWidgetByID("game_options_menu_right_panel")).Hidden     = false;
                ((Panel)_root.FindWidgetByID("display_options_menu_right_panel")).Hidden  = true;
            }

            FullScreenSettingsButtonPressedEvent fullscreenSBPE = evt as FullScreenSettingsButtonPressedEvent;

            if (fullscreenSBPE != null)
            {
                ((Label)_root.FindWidgetByID("Screen_Size_Settings_Dropdown_Label")).Content = "Screen Size: Full Screen";
                // Set to full screen
                CVars.Get <bool>("display_windowed")   = false;
                CVars.Get <bool>("display_borderless") = false;
                CVars.Get <bool>("display_fullscreen") = true;
                // Generate event to force GameManager to change to correct settings
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }
            WindowedSettingsButtonPressed windowedSBPE = evt as WindowedSettingsButtonPressed;

            if (windowedSBPE != null)
            {
                ((Label)_root.FindWidgetByID("Screen_Size_Settings_Dropdown_Label")).Content = "Screen Size: Windowed";
                // Set to windowed
                CVars.Get <bool>("display_windowed")   = true;
                CVars.Get <bool>("display_borderless") = false;
                CVars.Get <bool>("display_fullscreen") = false;
                // Generate event to force GameManager to change to correct settings
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }
            BorderlessWindowButtonPressedEvent borderlessWindowSBPE = evt as BorderlessWindowButtonPressedEvent;

            if (borderlessWindowSBPE != null)
            {
                ((Label)_root.FindWidgetByID("Screen_Size_Settings_Dropdown_Label")).Content = "Screen Size: Borderless";
                // Set to borderless window
                CVars.Get <bool>("display_windowed")   = false;
                CVars.Get <bool>("display_borderless") = true;
                CVars.Get <bool>("display_fullscreen") = false;
                // Generate event to force GameManager to change to correct settings
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }

            /*
             * AAFXAASettingsButtonPressedEvent aafxaaSBPE = evt as AAFXAASettingsButtonPressedEvent;
             * if (aafxaaSBPE != null)
             * {
             *  ((Label)_root.FindWidgetByID("FXAA_Settings_Dropdown_Label")).Content = "Anti-Alias: FXAA";
             *  CVars.Get<bool>("graphics_fxaa") = true;
             *  CVars.Get<bool>("graphics_feathering") = false;
             *  EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
             * }
             */
            AASMAASettingsButtonPressedEvent aasmaaSBPE = evt as AASMAASettingsButtonPressedEvent;

            if (aasmaaSBPE != null)
            {
                ((Label)_root.FindWidgetByID("AA_Settings_Dropdown_Label")).Content = "Anti-Alias: SMAA";
                CVars.Get <bool>("graphics_smaa")       = true;
                CVars.Get <bool>("graphics_feathering") = false;
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }
            AAFeatheringButtonPressedEvent aafeatherSBPE = evt as AAFeatheringButtonPressedEvent;

            if (aafeatherSBPE != null)
            {
                ((Label)_root.FindWidgetByID("AA_Settings_Dropdown_Label")).Content = "Anti-Alias: Feathering";
                CVars.Get <bool>("graphics_smaa")       = false;
                CVars.Get <bool>("graphics_feathering") = true;
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }
            AAOffButtonPressedEvent aaoffSBPE = evt as AAOffButtonPressedEvent;

            if (aaoffSBPE != null)
            {
                ((Label)_root.FindWidgetByID("AA_Settings_Dropdown_Label")).Content = "Anti-Alias: Off";
                CVars.Get <bool>("graphics_smaa")       = false;
                CVars.Get <bool>("graphics_feathering") = false;
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }

            RotateLeftSettingsButtonPressedEvent rlSBPE = evt as RotateLeftSettingsButtonPressedEvent;

            if (rlSBPE != null)
            {
                Console.WriteLine("rlSBPE");
                // Rotate Left Button Clicked, enter into button binding state
                bindingControl = BindingControl.rotate_counter_clockwise;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.primary : BindingMode.gamepad;

                /*
                 * bindingMode = BindingMode.primary;
                 * bindingGamepad = !_root.MouseMode;
                 */
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("primary_rotate_counter_clockwise")).isSelected = false;
            }
            RotateRightSettingsButtonPressedEvent rrSBPE = evt as RotateRightSettingsButtonPressedEvent;

            if (rrSBPE != null)
            {
                Console.WriteLine("rrSBPE");
                // Rotate Right Button Clicked, enter into button binding state
                bindingControl = BindingControl.rotate_clockwise;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.primary : BindingMode.gamepad;
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("primary_rotate_clockwise")).isSelected = false;
            }
            if (evt is SuperShieldSettingsButtonPressedEvent)
            {
                Console.WriteLine("Super Shield Pressed");
                bindingControl = BindingControl.super_shield;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.primary : BindingMode.gamepad;
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("primary_super_shield")).isSelected = false;
            }
            if (evt is SecondaryRotateLeftSettingsButtonPressedEvent)
            {
                Console.WriteLine("secondary_rlSBPE");
                // Rotate Left Button Clicked, enter into button binding state
                bindingControl = BindingControl.rotate_counter_clockwise;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.secondary : BindingMode.gamepad;
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("secondary_rotate_counter_clockwise")).isSelected = false;
            }
            if (evt is SecondaryRotateRightSettingsButtonPressedEvent)
            {
                Console.WriteLine("secondary_rrSBPE");
                // Rotate Right Button Clicked, enter into button binding state
                bindingControl = BindingControl.rotate_clockwise;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.secondary : BindingMode.gamepad;
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("secondary_rotate_clockwise")).isSelected = false;
            }
            if (evt is SecondarySuperShieldSettingsButtonPressedEvent)
            {
                Console.WriteLine("Super Shield Pressed");
                bindingControl = BindingControl.super_shield;
                bindingMode    = (_root.MouseMode == true) ? BindingMode.secondary : BindingMode.gamepad;
                _root.AutoControlModeSwitching = false;
                ((Button)_root.FindWidgetByID("secondary_super_shield")).isSelected = false;
            }
            if (evt is ResolutionButtonPressedEvent)
            {
                ((Label)_root.FindWidgetByID("Resolution_Button_Label")).Content = SetNextResolution();
                GameManager.Graphics.IsFullScreen       = false;
                GameManager.Graphics.HardwareModeSwitch = true;
                GameManager.Graphics.ApplyChanges();
                EventManager.Instance.QueueEvent(new ReloadDisplayOptionsEvent());
            }
            if (evt is VSyncButtonPressedEvent)
            {
                bool replacement = !(CVars.Get <bool>("display_vsync"));
                CVars.Get <bool>("display_vsync") = replacement;
                ((Label)_root.FindWidgetByID("VSync_Button_Label")).Content =
                    (replacement == true) ?
                    "V-Sync: On" :
                    "V-Sync: Off";
            }

            return(false);
        }
예제 #47
0
        private DataBinding AddBinding(string propertyName, BindingMode mode = BindingMode.OneWay, string listPropertyName = null, View view = null, AdapterView commandParameterSelectedItemAdapterView = null)
        {
            string idName     = (view != null) ? view.Id.ToString() : IdName(propertyName);
            int?   resourceId = AndroidHelpers.FindResourceId(idName);

            if (view == null && resourceId.HasValue)
            {
                view = rootView.FindViewById(resourceId.Value);
            }
            if (view == null)
            {
                return(null);
            }

            bool   itemIsValue = false;
            string itemTemplateName = null, itemValueId = null;
            int?   commandParameterListId = null;

            if (view.Tag != null)
            {
                // Get optional parameters from tag:
                // {Binding propertyName, Mode=OneWay|TwoWay|Command}
                // {List ItemsSource=listPropertyName, ItemIsValue=false|true, ItemTemplate=listItemTemplateName, ItemValueId=listItemValueId}
                // {CommandParameter ListId=<view Id>}
                // Defaults:
                //   propertyName is known by convention from view Id = <rootview prefix><propertyName>; the default for the rootview prefix is the rootview class name + "_".
                //   Mode = OneWay
                // Additional defaults for views derived from AdapterView (i.e. lists):
                //   ItemsSource = propertyName + "List"
                //   ItemIsValue = false
                //   ItemTemplate = ItemsSource + "Item"
                //   ItemValueId : if ItemIsValue = true then the default for ItemValueId = ItemTemplate
                string tag = view.Tag.ToString();
                if (tag != null && tag.Contains("{"))
                {
                    var match = Regex.Match(tag, @"({Binding\s+((?<assignment>[^,{}]+),?)+\s*})?(\s*{List\s+((?<assignment>[^,{}]+),?)+\s*})?(\s*{CommandParameter\s+((?<assignment>[^,{}]+),?)+\s*})?");
                    if (match.Success)
                    {
                        var gc = match.Groups["assignment"];
                        if (gc != null)
                        {
                            var cc = gc.Captures;
                            if (cc != null)
                            {
                                for (int i = 0; i < cc.Count; i++)
                                {
                                    string[] assignmentElements = cc[i].Value.Split('=');
                                    if (assignmentElements.Length == 1)
                                    {
                                        string value = assignmentElements[0].Trim();
                                        if (value != "")
                                        {
                                            propertyName = value;
                                        }
                                    }
                                    else if (assignmentElements.Length == 2)
                                    {
                                        string name  = assignmentElements[0].Trim();
                                        string value = assignmentElements[1].Trim();
                                        switch (name)
                                        {
                                        case "Mode": Enum.TryParse <BindingMode>(value, true, out mode); break;

                                        case "ItemsSource": listPropertyName = value; break;

                                        case "ItemIsValue": Boolean.TryParse(value, out itemIsValue); break;

                                        case "ItemTemplate": itemTemplateName = value; break;

                                        case "ItemValueId": itemValueId = value; break;

                                        case "ListId":
                                            commandParameterListId = AndroidHelpers.FindResourceId(value);
                                            if (commandParameterSelectedItemAdapterView == null && commandParameterListId.HasValue)
                                            {
                                                commandParameterSelectedItemAdapterView = rootView.FindViewById <AdapterView>(commandParameterListId.Value);
                                            }
                                            break;

                                        default: throw new ArgumentException("Unknown tag binding parameter: " + name);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            var binding = new DataBinding
            {
                View                     = view,
                ResourceId               = resourceId,
                Mode                     = mode,
                ViewModelPropertyInfo    = viewModel.GetType().GetProperty(propertyName),
                CommandParameterListId   = commandParameterListId,
                CommandParameterListView = commandParameterSelectedItemAdapterView
            };

            if (binding.View is AdapterView)
            {
                if (listPropertyName == null)
                {
                    listPropertyName = propertyName + "List";
                }
                var pi = viewModel.GetType().GetProperty(listPropertyName);
                if (pi == null && binding.ViewModelPropertyInfo.PropertyType.GetInterface("IList") != null)
                {
                    listPropertyName = propertyName;
                    pi = binding.ViewModelPropertyInfo;
                    binding.ViewModelPropertyInfo = null;
                }
                binding.ViewModelListPropertyInfo = pi;

                pi = binding.View.GetType().GetProperty("Adapter", BindingFlags.Public | BindingFlags.Instance);
                if (pi != null)
                {
                    var adapter = pi.GetValue(binding.View);
                    if (adapter == null)
                    {
                        if (itemTemplateName == null)
                        {
                            itemTemplateName = listPropertyName + "Item";
                        }
                        if (itemIsValue && itemValueId == null)
                        {
                            itemValueId = itemTemplateName;
                        }
                        int?itemTemplateResourceId = AndroidHelpers.FindResourceId(itemTemplateName, AndroidHelpers.ResourceCategory.Layout);
                        int?itemValueResourceId    = AndroidHelpers.FindResourceId(itemValueId);
                        if (itemTemplateResourceId.HasValue)
                        {
                            adapter = new DataBindableListAdapter <object>(layoutInflater, itemTemplateResourceId.Value, itemTemplateName + "_", itemValueResourceId, rootViewExtensionPoints);
                            pi.SetValue(binding.View, adapter);
                        }
                    }
                    binding.ListAdapter = adapter as IDataBindableListAdapter;
                }
            }

            switch (binding.Mode)
            {
            case BindingMode.TwoWay: AddTwoWayHandler(binding); break;

            case BindingMode.Command: AddCommandHandler(binding); break;
            }

            dataBindings.Add(idName, binding);
            return(binding);
        }
예제 #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Binding"/> class.
 /// </summary>
 /// <param name="mode">The binding mode.</param>
 public BindingBase(BindingMode mode = BindingMode.Default)
     : this()
 {
     Mode = mode;
 }
예제 #49
0
        public static Binding Create <TSource>(Expression <Func <TSource, object> > propertyGetter, BindingMode mode = BindingMode.Default, IValueConverter converter = null, object converterParameter = null,
                                               string stringFormat = null)
        {
            if (propertyGetter == null)
            {
                throw new ArgumentNullException("propertyGetter");
            }

            string path = GetBindingPath(propertyGetter);

            return(new Binding(path, mode, converter, converterParameter, stringFormat));
        }
예제 #50
0
 public static void ActInputValueBinding(System.Windows.Controls.Control control, DependencyProperty dependencyProperty, ActInputValue actInputValue, IValueConverter bindingConvertor = null, BindingMode BindingMode = BindingMode.TwoWay)
 {
     ObjFieldBinding(control, dependencyProperty, actInputValue, nameof(ActInputValue.Value), bindingConvertor, BindingMode);
 }
예제 #51
0
 public static void BindControl(this TextBox TextBox, Object obj, string Field, BindingMode bm = BindingMode.TwoWay)
 {
     GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(TextBox, TextBox.TextProperty, obj, Field, bm);
 }
예제 #52
0
        public static void ObjFieldBinding(System.Windows.Controls.Control control, DependencyProperty dependencyProperty, object obj, string property, IValueConverter bindingConvertor, BindingMode BindingMode = BindingMode.TwoWay)
        {
            //TODO: add Inotify on the obj.attr - so code changes to property will be reflected
            //TODO: check perf impact + reuse exisitng binding on same obj.prop
            try
            {
                System.Windows.Data.Binding b = new System.Windows.Data.Binding();
                b.Source = obj;
                b.Path   = new PropertyPath(property);
                b.Mode   = BindingMode;
                if (bindingConvertor != null)
                {
                    b.Converter = bindingConvertor;
                }
                b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                control.SetBinding(dependencyProperty, b);
            }
            catch (Exception ex)
            {
                //it is possible we load an old enum or something else which will cause the binding to fail
                // Can happen also if the bind field name is incorrect
                // mark the control in red, instead of not openning the Page
                // Set a tool tip with the error

                // control.IsEnabled = false; // Do not disable as the red will not show
                control.Style = null; // remove style so red will show
                //control.Foreground = System.Windows.Media.Brushes.Red;
                control.Background      = System.Windows.Media.Brushes.LightPink;
                control.BorderThickness = new Thickness(2);
                control.BorderBrush     = System.Windows.Media.Brushes.Red;

                control.ToolTip = "Error binding control to property: " + Environment.NewLine + property + " Please open a defect with all information,  " + Environment.NewLine + ex.Message;
            }
        }
예제 #53
0
        /// <summary>
        ///     Applies the binding expression to a previously set source or target.
        /// </summary>
        void ApplyCore(object sourceObject, BindableObject target, BindableProperty property, bool fromTarget = false)
        {
            BindingMode mode = Binding.GetRealizedMode(_targetProperty);

            if ((mode == BindingMode.OneWay || mode == BindingMode.OneTime) && fromTarget)
            {
                return;
            }

            bool needsGetter = (mode == BindingMode.TwoWay && !fromTarget) || mode == BindingMode.OneWay || mode == BindingMode.OneTime;
            bool needsSetter = !needsGetter && ((mode == BindingMode.TwoWay && fromTarget) || mode == BindingMode.OneWayToSource);

            object current             = sourceObject;
            BindingExpressionPart part = null;

            for (var i = 0; i < _parts.Count; i++)
            {
                part = _parts[i];

                if (!part.IsSelf && current != null)
                {
                    // Allow the object instance itself to provide its own TypeInfo
                    TypeInfo currentType = current is IReflectableType reflectable?reflectable.GetTypeInfo() : current.GetType().GetTypeInfo();

                    if (part.LastGetter == null || !part.LastGetter.DeclaringType.GetTypeInfo().IsAssignableFrom(currentType))
                    {
                        SetupPart(currentType, part);
                    }

                    if (i < _parts.Count - 1)
                    {
                        part.TryGetValue(current, out current);
                    }
                }

                if (!part.IsSelf &&
                    current != null &&
                    ((needsGetter && part.LastGetter == null) ||
                     (needsSetter && part.NextPart == null && part.LastSetter == null)))
                {
                    BindingDiagnostics.SendBindingFailure(Binding, current, target, property, "Binding", PropertyNotFoundErrorMessage, part.Content, current, target.GetType(), property.PropertyName);
                    break;
                }

                if (part.NextPart != null && (mode == BindingMode.OneWay || mode == BindingMode.TwoWay) &&
                    current is INotifyPropertyChanged inpc)
                {
                    part.Subscribe(inpc);
                }
            }

            Debug.Assert(part != null, "There should always be at least the self part in the expression.");

            if (needsGetter)
            {
                if (part.TryGetValue(current, out object value) || part.IsSelf)
                {
                    value = Binding.GetSourceValue(value, property.ReturnType);
                }
                else
                {
                    value = Binding.FallbackValue ?? property.GetDefaultValue(target);
                }

                if (!TryConvert(ref value, property, property.ReturnType, true))
                {
                    BindingDiagnostics.SendBindingFailure(Binding, current, target, property, "Binding", CannotConvertTypeErrorMessage, value, property.ReturnType);
                    return;
                }

                target.SetValueCore(property, value, SetValueFlags.ClearDynamicResource, BindableObject.SetValuePrivateFlags.Default | BindableObject.SetValuePrivateFlags.Converted);
            }
            else if (needsSetter && part.LastSetter != null && current != null)
            {
                object value = Binding.GetTargetValue(target.GetValue(property), part.SetterType);

                if (!TryConvert(ref value, property, part.SetterType, false))
                {
                    BindingDiagnostics.SendBindingFailure(Binding, current, target, property, "Binding", CannotConvertTypeErrorMessage, value, part.SetterType);
                    return;
                }

                object[] args;
                if (part.IsIndexer)
                {
                    args = new object[part.Arguments.Length + 1];
                    part.Arguments.CopyTo(args, 0);
                    args[args.Length - 1] = value;
                }
                else if (part.IsBindablePropertySetter)
                {
                    args = new[] { part.BindablePropertyField, value };
                }
                else
                {
                    args = new[] { value };
                }

                part.LastSetter.Invoke(current, args);
            }
        }
예제 #54
0
        public static void ObjFieldBinding(TextBlock textBlockControl, DependencyProperty dependencyProperty, object obj, string property, BindingMode BindingMode = BindingMode.TwoWay)
        {
            //TODO: add Inotify on the obj.attr - so code changes to property will be reflected
            //TODO: check perf impact + reuse exisitng binding on same obj.prop
            try
            {
                Binding b = new Binding();
                b.Source = obj;
                b.Path   = new PropertyPath(property);
                b.Mode   = BindingMode;
                b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                textBlockControl.SetBinding(dependencyProperty, b);
            }
            catch (Exception ex)
            {
                //it is possible we load an old enum or something else which will cause the binding to fail
                // Can happen also if the bind field name is incorrect
                // mark the control in red, instead of not openning the Page
                // Set a tool tip with the error

                textBlockControl.Style      = null; // remove style so red will show
                textBlockControl.Background = System.Windows.Media.Brushes.LightPink;
                textBlockControl.ToolTip    = "Error binding control to property: " + Environment.NewLine + property + " Please open a defect with all information,  " + Environment.NewLine + ex.Message;
            }
        }
예제 #55
0
파일: Tool.cs 프로젝트: jume2003/SK800
        public static void BindingValue(String Path, DependencyProperty TargetProperty, FrameworkElement Target, BindingMode bindingMode = BindingMode.TwoWay)
        {
            Binding bindingValue = new Binding(Path)
            {
                Mode = bindingMode
            };

            bindingValue.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            Target.SetBinding(TargetProperty, bindingValue);
        }
예제 #56
0
        public static void SetBinding(this BindableObject self, BindableProperty targetProperty, string path, BindingMode mode = BindingMode.Default, IValueConverter converter = null,
                                      string stringFormat = null)
        {
            if (self == null)
            {
                throw new ArgumentNullException("self");
            }
            if (targetProperty == null)
            {
                throw new ArgumentNullException("targetProperty");
            }

            var binding = new Binding(path, mode, converter, stringFormat: stringFormat);

            self.SetBinding(targetProperty, binding);
        }
예제 #57
0
파일: Binding.cs 프로젝트: xubinvc/Catel
 /// <summary>
 /// Initializes a new instance of the <see cref="Binding"/> class.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="sourcePropertyName">Name of the source property.</param>
 /// <param name="target">The target.</param>
 /// <param name="targetPropertyName">Name of the target property.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="converter">The converter.</param>
 /// <exception cref="ArgumentNullException">The <paramref name="source"/> is <c>null</c>.</exception>
 /// <exception cref="ArgumentNullException">The <paramref name="target"/> is <c>null</c>.</exception>
 public Binding(object source, string sourcePropertyName, object target, string targetPropertyName, BindingMode mode = BindingMode.TwoWay,
                IValueConverter converter = null)
     : this(new BindingParty(source, sourcePropertyName), new BindingParty(target, targetPropertyName), mode, converter)
 {
 }
 public static BindableProperty Create <TDeclarer, TPropertyType>(Expression <Func <TDeclarer, TPropertyType> > getter, TPropertyType defaultValue, BindingMode defaultBindingMode = BindingMode.OneWay,
                                                                  ValidateValueDelegate <TPropertyType> validateValue = null, BindingPropertyChangedDelegate <TPropertyType> propertyChanged        = null,
                                                                  BindingPropertyChangingDelegate <TPropertyType> propertyChanging          = null, CoerceValueDelegate <TPropertyType> coerceValue = null,
                                                                  CreateDefaultValueDelegate <TDeclarer, TPropertyType> defaultValueCreator = null) where TDeclarer : BindableObject
 {
     return(Create(getter, defaultValue, defaultBindingMode, validateValue, propertyChanged, propertyChanging, coerceValue, null, defaultValueCreator: defaultValueCreator));
 }
        internal static BindableProperty CreateAttached <TDeclarer, TPropertyType>(Expression <Func <BindableObject, TPropertyType> > staticgetter, TPropertyType defaultValue, BindingMode defaultBindingMode,
                                                                                   ValidateValueDelegate <TPropertyType> validateValue, BindingPropertyChangedDelegate <TPropertyType> propertyChanged, BindingPropertyChangingDelegate <TPropertyType> propertyChanging,
                                                                                   CoerceValueDelegate <TPropertyType> coerceValue, BindablePropertyBindingChanging bindingChanging, bool isReadOnly = false,
                                                                                   CreateDefaultValueDelegate <BindableObject, TPropertyType> defaultValueCreator = null)
        {
            if (staticgetter == null)
            {
                throw new ArgumentNullException("staticgetter");
            }

            Expression expr = staticgetter.Body;

            var unary = expr as UnaryExpression;

            if (unary != null)
            {
                expr = unary.Operand;
            }

            var methodcall = expr as MethodCallExpression;

            if (methodcall == null)
            {
                throw new ArgumentException("staticgetter must be a MethodCallExpression", "staticgetter");
            }

            MethodInfo method = methodcall.Method;

            if (!method.Name.StartsWith("Get", StringComparison.Ordinal))
            {
                throw new ArgumentException("staticgetter name must start with Get", "staticgetter");
            }

            string propertyname = method.Name.Substring(3);

            ValidateValueDelegate           untypedValidateValue           = null;
            BindingPropertyChangedDelegate  untypedBindingPropertyChanged  = null;
            BindingPropertyChangingDelegate untypedBindingPropertyChanging = null;
            CoerceValueDelegate             untypedCoerceValue             = null;
            CreateDefaultValueDelegate      untypedDefaultValueCreator     = null;

            if (validateValue != null)
            {
                untypedValidateValue = (bindable, value) => validateValue(bindable, (TPropertyType)value);
            }
            if (propertyChanged != null)
            {
                untypedBindingPropertyChanged = (bindable, oldValue, newValue) => propertyChanged(bindable, (TPropertyType)oldValue, (TPropertyType)newValue);
            }
            if (propertyChanging != null)
            {
                untypedBindingPropertyChanging = (bindable, oldValue, newValue) => propertyChanging(bindable, (TPropertyType)oldValue, (TPropertyType)newValue);
            }
            if (coerceValue != null)
            {
                untypedCoerceValue = (bindable, value) => coerceValue(bindable, (TPropertyType)value);
            }
            if (defaultValueCreator != null)
            {
                untypedDefaultValueCreator = o => defaultValueCreator(o);
            }

            return(new BindableProperty(propertyname, method.ReturnType, typeof(TDeclarer), defaultValue, defaultBindingMode, untypedValidateValue, untypedBindingPropertyChanged, untypedBindingPropertyChanging,
                                        untypedCoerceValue, bindingChanging, isReadOnly, untypedDefaultValueCreator));
        }
        public static BindablePropertyKey CreateAttachedReadOnly <TDeclarer, TPropertyType>(Expression <Func <BindableObject, TPropertyType> > staticgetter, TPropertyType defaultValue,
                                                                                            BindingMode defaultBindingMode = BindingMode.OneWayToSource, ValidateValueDelegate <TPropertyType> validateValue = null,
                                                                                            BindingPropertyChangedDelegate <TPropertyType> propertyChanged = null, BindingPropertyChangingDelegate <TPropertyType> propertyChanging = null,
                                                                                            CoerceValueDelegate <TPropertyType> coerceValue = null, CreateDefaultValueDelegate <BindableObject, TPropertyType> defaultValueCreator  = null)

        {
            return
                (new BindablePropertyKey(CreateAttached <TDeclarer, TPropertyType>(staticgetter, defaultValue, defaultBindingMode, validateValue, propertyChanged, propertyChanging, coerceValue, null, true,
                                                                                   defaultValueCreator)));
        }