object IExpressionBinder.GetValue( HtmlBindingContext context, BindingExpression expression )
    {

      var dataModel = GetDataObject( context, expression );

      if ( dataModel == null )
        return null;


      CssElementSelector elementSelector = null;
      string selector;

      if ( expression.TryGetValue( context, "selector", out selector ) )
        elementSelector = CssParser.ParseElementSelector( selector );

      ListBindingMode mode;

      string modeSetting;
      if ( expression.TryGetValue( context, "mode", out modeSetting ) && modeSetting.EqualsIgnoreCase( "static" ) )
        mode = ListBindingMode.StaticContent;
      
      else
        mode = ListBindingMode.DynamicContent;



      return new ListDataModel( (IEnumerable) dataModel, elementSelector, mode );

    }
        protected virtual void OnAssociatedObjectLoaded()
        {
            var frameworkElement = ((FrameworkElement) AssociatedObject);
            frameworkElement.DataContextChanged += OnDataContextChanged;

            _expression = GetBindingExpressionToValidate(frameworkElement);
            _viewModel = frameworkElement.DataContext as INotifyPropertyChanged;

            var triggerValidate = (ITriggerValidate) _viewModel;
            if (triggerValidate != null)
            {
                _canValidate = triggerValidate.CanValidate;
                triggerValidate.CanValidateChanged += () =>
                {
                    _canValidate = triggerValidate.CanValidate;
                    Refresh();
                };
            }
            else
            {
                throw new InvalidOperationException("The view model must implement the ITriggerValidate interface");
            }

            HookPropertyChangedAndRefresh();
        }
Example #3
0
    /// <summary>
    /// 获取绑定值
    /// </summary>
    /// <param name="context">绑定上下文</param>
    /// <param name="arguments">绑定参数</param>
    /// <returns>绑定值</returns>
    public static string GetValue( HtmlBindingContext context, BindingExpression expression )
    {

      var dataObject = GetDataObject( context, expression );

      if ( dataObject == null )
        return null;

      {
        string format;
        if ( expression.TryGetValue( context, "format", out format ) )
        {

          if ( format.Contains( "{0" ) )
            return string.Format( CultureInfo.InvariantCulture, format, dataObject );

          else
          {
            var formattable = dataObject as IFormattable;

            if ( formattable != null )
              return formattable.ToString( format, CultureInfo.InvariantCulture );

            else
              return dataObject.ToString();
          }
        }
      }



      return dataObject.ToString();

    }
		public void ApplyNull()
		{
			const string path = "Foo.Bar";
			var binding = new Binding (path);
			var be = new BindingExpression (binding, path);
			Assert.DoesNotThrow (() => be.Apply (null, new MockBindable(), TextCell.TextProperty));
		}
 public TwoWayPropertyBinding(BindingExpression expression, object targetObject)
     : base(expression, targetObject)
 {
     if (string.IsNullOrEmpty(expression.UpdateEvent))
     {
         throw new Exception("TwoWayPropertyBinding : can not update in two way mode without an event");
     }
 }
Example #6
0
		internal override void Apply(bool fromTarget)
		{
			base.Apply(fromTarget);

			if (_expression == null)
				_expression = new BindingExpression(this, SelfPath);

			_expression.Apply(fromTarget);
		}
        public virtual void Detach()
        {
            ((FrameworkElement) AssociatedObject).DataContextChanged -= OnDataContextChanged;
            AssociatedObject = null;

            _viewModel.PropertyChanged -= ViewModel_PropertyChanged;
            _viewModel = null;
            _expression = null;
            _validator = null;
        }
		public void Ctor()
		{
			string path = "Foo.Bar";
			var binding = new Binding (path);
			
			var be = new BindingExpression (binding, path);

			Assert.AreSame (binding, be.Binding);
			Assert.AreEqual (path, be.Path);
		}
Example #9
0
    /// <summary>
    /// 根据绑定参数获取数据对象
    /// </summary>
    /// <param name="context">绑定上下文</param>
    /// <param name="arguments">绑定参数</param>
    /// <returns>数据对象</returns>
    public static object GetDataObject( HtmlBindingContext context, BindingExpression expression )
    {
      object dataObject  = context.DataModel;




      if ( dataObject != null )
      {
        string path;

        if ( expression.TryGetValue( context, "path", out path ) )
        {

          if ( dataObject == null )
            return null;

          dataObject = DataBinder.Eval( dataObject, path );
        }
      }

      object value;
      if ( expression.TryGetValue( context, "value", out value ) )
      {
        if ( dataObject != null && Convert.ToBoolean( dataObject ) == true )
          return value;

        else if ( expression.TryGetValue( context, "alternativeValue", out value ) )
          return value;

        else
          return null;
      }

      return dataObject;
    }
Example #10
0
 /// <summary>
 /// ビヘイビア解除
 /// </summary>
 protected override void OnDetaching()
 {
     _Binding = null;
     base.OnDetaching();
 }
Example #11
0
        private void ElementSizer_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            BindingExpression bindingExpression = (sender as ElementSizer).Element.GetBindingExpression(WidthProperty);

            bindingExpression.UpdateSource();
        }
Example #12
0
 protected BindingBase(BindingExpression expression, object targetObject)
 {
     Expression = expression;
     TargetObject = targetObject;
 }
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            //Check for Validation Error
            BindingExpression debitNoteDateBe         = debitNoteDateText.GetBindingExpression(DatePicker.SelectedDateProperty);
            BindingExpression commissionRateBe        = commissionRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression charityRateBe           = charityRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression brokeageRateBe          = brokerageRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression postageCostBe           = postageCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression cottonDeliveryExpRateBe = cottonDeliveryExpText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression jafferyActualCostBe     = jafferyActualCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression markingRateBe           = markingRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression sampleCuttingCostBe     = sampleCuttingCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression cartagePlatformRateBe   = cartageFactoryRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression stackingRateBe          = stackingRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression katlaExpRateBe          = katlaExpRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression cartageFactoryRateBe    = cartageFactoryRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression stationExpRateBe        = stationExpText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression truckLoadingRateBe      = truckLoadingRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression bankChargeRateBe        = bankChargeCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression godownRentFromBe        = godownRentFromText.GetBindingExpression(DatePicker.SelectedDateProperty);
            BindingExpression godownRentToBe          = godownRentToText.GetBindingExpression(DatePicker.SelectedDateProperty);
            BindingExpression godownRentCostBe        = godownRentCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression stockInsuranceCostBe    = stockInsuranceCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression freightFromBe           = freightFromText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression freightToBe             = freightToText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression freightCostBe           = freightCostText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression carringChargesOnBe      = carringChargesOnText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression carringChargesFromBe    = carringChargesFromText.GetBindingExpression(DatePicker.SelectedDateProperty);
            BindingExpression carringChargesToBe      = carringChargesToText.GetBindingExpression(DatePicker.SelectedDateProperty);
            BindingExpression carringChargesRateBe    = carringChargesRateText.GetBindingExpression(TextBox.TextProperty);
            BindingExpression amountAndVatRateBe      = amountAndVatRateText.GetBindingExpression(TextBox.TextProperty);

            debitNoteDateBe.UpdateSource();
            commissionRateBe.UpdateSource();
            charityRateBe.UpdateSource();
            brokeageRateBe.UpdateSource();
            postageCostBe.UpdateSource();
            cottonDeliveryExpRateBe.UpdateSource();
            jafferyActualCostBe.UpdateSource();
            markingRateBe.UpdateSource();
            sampleCuttingCostBe.UpdateSource();
            cartagePlatformRateBe.UpdateSource();
            stackingRateBe.UpdateSource();
            katlaExpRateBe.UpdateSource();
            cartageFactoryRateBe.UpdateSource();
            stationExpRateBe.UpdateSource();
            truckLoadingRateBe.UpdateSource();
            bankChargeRateBe.UpdateSource();
            godownRentFromBe.UpdateSource();
            godownRentToBe.UpdateSource();
            godownRentCostBe.UpdateSource();
            stockInsuranceCostBe.UpdateSource();
            freightFromBe.UpdateSource();
            freightToBe.UpdateSource();
            freightCostBe.UpdateSource();
            carringChargesOnBe.UpdateSource();
            carringChargesFromBe.UpdateSource();
            carringChargesToBe.UpdateSource();
            carringChargesRateBe.UpdateSource();
            amountAndVatRateBe.UpdateSource();

            if (debitNoteDateBe.HasError || commissionRateBe.HasError || charityRateBe.HasError || brokeageRateBe.HasError || postageCostBe.HasError || cottonDeliveryExpRateBe.HasError ||
                jafferyActualCostBe.HasError || markingRateBe.HasError || sampleCuttingCostBe.HasError || cartagePlatformRateBe.HasError || stackingRateBe.HasError || katlaExpRateBe.HasError ||
                cartageFactoryRateBe.HasError || stationExpRateBe.HasError || truckLoadingRateBe.HasError || bankChargeRateBe.HasError || godownRentFromBe.HasError || godownRentToBe.HasError ||
                stockInsuranceCostBe.HasError || freightFromBe.HasError || freightToBe.HasError || carringChargesOnBe.HasError || carringChargesFromBe.HasError || carringChargesToBe.HasError ||
                carringChargesRateBe.HasError || godownRentCostBe.HasError || freightCostBe.HasError || amountAndVatRateBe.HasError)
            {
                MessageBox.Show("Please correct Errors", "Insert Aborted");
            }
            else
            {
                editMessage = ((DebitNotes)this.DataContext).Update();
                MessageBox.Show(editMessage, "Invoice");
                this.NavigationService.Navigate(new Uri("DebitNote.xaml", UriKind.Relative));
            }
        }
Example #14
0
        private static void UpdateEffectiveValue(INTERNAL_PropertyStorage storage,
                                                 object newValue,
                                                 BaseValueSourceInternal newValueSource,
                                                 bool coerceWithCurrentValue,
                                                 bool coerceValue,
                                                 bool clearValue,
                                                 bool propagateChanges)
        {
            global::System.Diagnostics.Debug.Assert((coerceWithCurrentValue == coerceValue && !coerceValue) || coerceValue != coerceWithCurrentValue);

            bool isCoerceOperation = coerceValue || coerceWithCurrentValue;
            BaseValueSourceInternal oldBaseValueSource = storage.BaseValueSourceInternal;

            object            oldValue;
            BindingExpression currentExpr = null;

            // Compute new value
            object effectiveValue;
            BaseValueSourceInternal effectiveValueKind;

            if (isCoerceOperation)
            {
                // Source and base value are unchanged during coercion operation
                effectiveValue     = newValue;
                effectiveValueKind = oldBaseValueSource;

                // Get old value before it gets overriden
                oldValue = GetEffectiveValue(storage);
            }
            else
            {
                ComputeEffectiveValue(storage, out effectiveValue, out effectiveValueKind);

                // Check for early exit if effective value is not impacted (if we are doing
                // a coerce operation, we have to go through the update process)
                if (effectiveValueKind == oldBaseValueSource &&
                    newValueSource < effectiveValueKind)
                {
                    // value source remains the same.
                    // Exit if the newly set value is of lower precedence than the effective value.
                    return;
                }

                // Get old value before it gets overriden
                oldValue = GetEffectiveValue(storage);

                currentExpr = (storage.IsExpression || storage.IsExpressionFromStyle) ? storage.ModifiedValue.BaseValue as BindingExpression : null;

                // If the current base value is a BindingExpression, it should have been detached by now
                // Or is the same instance as 'effectiveValue' (this occurs when we update a property bound to a
                // BindingExpression)
                global::System.Diagnostics.Debug.Assert(currentExpr == null ||
                                                        !currentExpr.IsAttached ||
                                                        object.ReferenceEquals(currentExpr, effectiveValue), "Binding expression should be detached.");

                storage.ResetValue();

                // Update the base value source
                storage.BaseValueSourceInternal = effectiveValueKind;
            }

            object computedValue;

            if (!isCoerceOperation)
            {
                BindingExpression newExpr = effectiveValue as BindingExpression;
                if (newExpr == null)
                {
                    computedValue = storage.Property.PropertyType == typeof(string)
                                    ? effectiveValue?.ToString()
                                    : effectiveValue;
                    storage.Value = computedValue;
                }
                else
                {
                    global::System.Diagnostics.Debug.Assert(effectiveValueKind == BaseValueSourceInternal.Local || effectiveValueKind == BaseValueSourceInternal.LocalStyle);

                    // If the new BindingExpression is the same as the current one,
                    // the BindingExpression is already attached
                    bool isNewBinding = !object.ReferenceEquals(currentExpr, newExpr);
                    if (isNewBinding)
                    {
                        if (newExpr.IsAttached)
                        {
                            throw new InvalidOperationException(string.Format("Cannot attach an instance of '{0}' multiple times", typeof(BindingExpression)));
                        }
                        newExpr.OnAttached(storage.Owner);
                        storage.Value = newExpr; // Set the new base value
                    }

                    if (effectiveValueKind == BaseValueSourceInternal.Local)
                    {
                        storage.SetExpressionValue(storage.TypeMetadata.DefaultValue, newExpr);
                    }
                    else
                    {
                        storage.SetExpressionFromStyleValue(storage.TypeMetadata.DefaultValue, newExpr);
                    }

                    // 1- 'isNewBinding == true' means that we are attaching a new BindingExpression.
                    // 2- 'newValue is BindingExpression == true' means that we are re-evaluating a BindingEpression
                    // (usually by calling RefreshBindingExpressionCommon)
                    // 3- Otherwise we are trying to change the value of a TwoWay binding.
                    // In that case we have to preserve the BindingExpression (this is not the case if the first two
                    // situations), hence the following line :
                    computedValue = isNewBinding || newValue is BindingExpression?newExpr.GetValue(storage.Property, storage.Owner.GetType())
                                        : newValue;

                    computedValue = storage.Property.PropertyType == typeof(string)
                                    ? computedValue?.ToString()
                                    : computedValue;
                    storage.ModifiedValue.ExpressionValue = computedValue;
                }
            }
            else
            {
                computedValue = coerceWithCurrentValue ? newValue : GetCoercionBaseValue(storage);
                if (coerceValue)
                {
                    storage.ResetCoercedValue();
                }
            }

            // Coerce to current value
            if (coerceWithCurrentValue)
            {
                object baseValue = GetCoercionBaseValue(storage);
                ProcessCoerceValue(storage,
                                   ref computedValue,
                                   oldValue,
                                   baseValue,
                                   true);
            }

            // Coerce Value
            // We don't want to coerce the value if it's being reset to the property's default value
            if (storage.TypeMetadata.CoerceValueCallback != null && !(clearValue && storage.FullValueSource == (FullValueSource)BaseValueSourceInternal.Default))
            {
                object baseValue = GetCoercionBaseValue(storage);
                ProcessCoerceValue(storage,
                                   ref computedValue,
                                   oldValue,
                                   baseValue,
                                   false);
            }

            // Reset old value inheritance context
            if (oldBaseValueSource == BaseValueSourceInternal.Local)
            {
                // Notes:
                // - Inheritance context is only handled by local value
                // - We use null instead of the actual DependencyProperty
                // as the parameter is ignored in the current implentation.
                storage.Owner.RemoveSelfAsInheritanceContext(oldValue, null /*storage.Property*/);
            }

            // Set new value inheritance context
            if (effectiveValueKind == BaseValueSourceInternal.Local)
            {
                // Check above
                storage.Owner.ProvideSelfAsInheritanceContext(computedValue, null /*storage.Property*/);
            }

            if (!ArePropertiesEqual(oldValue, computedValue, storage.Property.PropertyType))
            {
                // Raise the PropertyChanged event
                if (!storage.TypeMetadata.Inherits || ShouldRaisePropertyChanged(storage))
                {
                    OnPropertyChanged(storage, oldValue, computedValue);
                }

                // Propagate to children if property is inherited
                if (storage.TypeMetadata.Inherits && propagateChanges)
                {
                    CascadeInheritedPropertyToChildren(storage, computedValue);
                }
            }

            // Update the source of the Binding, in case the previous value of a property was a Binding and the Mode was "TwoWay":
            if (currentExpr != null && currentExpr.ParentBinding.Mode == BindingMode.TwoWay) //note: we know that oldBindingExpression.IsUpdating is false because oldBindingExpression is only set in that case (otherwise, it is null).
            {
                currentExpr.TryUpdateSourceObject(computedValue);
            }
        }
Example #15
0
        private void Valid_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression _binding = lblSampleText.GetBindingExpression(TextBox.TextProperty);

            _binding.UpdateSource();
        }
        private string GetValuePropertyBindingPath(DataGridColumn column)
        {
            string path = DataGridColumnExtensions.GetFilterMemberPathProperty(column);

            if (path == null)
            {
                path = String.Empty;

                if (column is DataGridBoundColumn)
                {
                    DataGridBoundColumn bc = column as DataGridBoundColumn;
                    path = (bc.Binding as Binding).Path.Path;
                }
                else if (column is DataGridTemplateColumn)
                {
                    DataGridTemplateColumn tc = column as DataGridTemplateColumn;

                    object templateContent = tc.CellTemplate.LoadContent();

                    if (templateContent != null && templateContent is TextBlock)
                    {
                        TextBlock block = templateContent as TextBlock;

                        BindingExpression binding = block.GetBindingExpression(TextBlock.TextProperty);

                        path = binding.ParentBinding.Path.Path;
                    }
                    else if (templateContent != null && templateContent is Button)
                    {
                        Button block = templateContent as Button;

                        BindingExpression binding = block.GetBindingExpression(Button.ContentProperty);

                        path = binding.ParentBinding.Path.Path;
                    }
                }
                else if (column is DataGridComboBoxColumn)
                {
                    DataGridComboBoxColumn comboColumn = column as DataGridComboBoxColumn;

                    path = null;

                    Binding binding = ((comboColumn.SelectedValueBinding) as Binding);

                    if (binding == null)
                    {
                        binding = ((comboColumn.SelectedItemBinding) as Binding);
                    }

                    if (binding == null)
                    {
                        binding = comboColumn.SelectedValueBinding as Binding;
                    }

                    if (binding != null)
                    {
                        path = binding.Path.Path;
                    }

                    if (comboColumn.SelectedItemBinding != null && comboColumn.SelectedValueBinding == null)
                    {
                        if (path != null && path.Trim().Length > 0)
                        {
                            if (DataGridComboBoxExtensions.GetIsTextFilter(comboColumn))
                            {
                                path += "." + comboColumn.DisplayMemberPath;
                            }
                            else
                            {
                                path += "." + comboColumn.SelectedValuePath;
                            }
                        }
                    }
                }
            }

            return(path);
        }
Example #17
0
        /// <summary>
        /// Inialize necessary properties and hook necessary events on TextBox, then add it into tree.
        /// </summary>
        private void BuildTextBox()
        {
            if (_textBox == null)
            {
                _textBox = new TextBox();
                _textBox.BorderThickness  = new Thickness(1);
                _textBox.BorderBrush      = Brushes.Black;
                _textBox.Background       = Brushes.White;
                _textBox.Padding          = new Thickness(0);
                _textBox.Margin           = new Thickness(0);
                _textBox.IsHitTestVisible = true;
                _textBox.KeyDown         +=
                    (KeyEventHandler) delegate(object sender, KeyEventArgs args)
                {
                    if (_editBox.IsEditing && (args.Key == Key.Enter || args.Key == Key.Escape))
                    {
                        if (args.Key == Key.Escape)
                        {
                            BindingExpression bexp = _editBox.GetBindingExpression(EditBox.ActualValueProperty);
                            bexp.UpdateTarget();
                        }
                        _editBox.IsEditing  = false;
                        _editBox._canBeEdit = false;
                        args.Handled        = true;
                    }
                };
                _textBox.GotKeyboardFocus +=
                    (KeyboardFocusChangedEventHandler) delegate(object sender, KeyboardFocusChangedEventArgs e)
                {
                    TextBox tb = (_textBox as TextBox);
                    tb.SelectionStart = tb.Text.Length;
                };
                _textBox.LostKeyboardFocus +=
                    (KeyboardFocusChangedEventHandler) delegate(object sender, KeyboardFocusChangedEventArgs e)
                {
                    BindingExpression bexp = _textBox.GetBindingExpression(TextBox.TextProperty);
                    bexp.UpdateSource();
                    _editBox.IsEditing = false;
                };
            }

            _canvas = new Canvas();
            _canvas.Children.Add(_textBox);
            _visualChildren.Add(_canvas);

            //Bind Text onto AdornedElement.
            Binding binding = new Binding("ActualValue");

            binding.Mode = BindingMode.TwoWay;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
            binding.Source = _editBox;


            _textBox.SetBinding(TextBox.TextProperty, binding);


            //Binding binding = new Binding("Text");

            //Update TextBox's focus status when layout finishs.
            _textBox.LayoutUpdated += new EventHandler(
                (EventHandler) delegate(object sender, EventArgs args)
            {
                if (_isVisible)
                {
                    _textBox.Focus();
                }
            });
            _textBox.Background   = Brushes.Transparent;
            _textBox.TextWrapping = TextWrapping.NoWrap;

            ScrollViewer.SetCanContentScroll(_textBox, false);
            ScrollViewer.SetVerticalScrollBarVisibility(_textBox, ScrollBarVisibility.Disabled);
            ScrollViewer.SetHorizontalScrollBarVisibility(_textBox, ScrollBarVisibility.Disabled);

            _textBox.GotFocus += delegate
            {
                _textBox.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                                                new ThreadStart(delegate
                {
                    int pos = _textBox.Text.LastIndexOf(".");
                    if (pos == -1)
                    {
                        _textBox.SelectAll();
                    }
                    else
                    {
                        _textBox.Select(0, pos);
                    }
                }));
            };
        }
Example #18
0
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            int selectionStart  = (_selectedDateTimeInfo != null) ? _selectedDateTimeInfo.StartPosition : 0;
            int selectionLength = (_selectedDateTimeInfo != null) ? _selectedDateTimeInfo.Length : 0;

            switch (e.Key)
            {
            case Key.Enter:
            {
                if (!IsReadOnly)
                {
                    _fireSelectionChangedEvent = false;
                    BindingExpression binding = BindingOperations.GetBindingExpression(TextBox, System.Windows.Controls.TextBox.TextProperty);
                    binding.UpdateSource();
                    _fireSelectionChangedEvent = true;
                }
                return;
            }

            case Key.Add:
                if (this.AllowSpin && !this.IsReadOnly)
                {
                    this.DoIncrement();
                    e.Handled = true;
                }
                _fireSelectionChangedEvent = false;
                break;

            case Key.Subtract:
                if (this.AllowSpin && !this.IsReadOnly)
                {
                    this.DoDecrement();
                    e.Handled = true;
                }
                _fireSelectionChangedEvent = false;
                break;

            case Key.Right:
                if (this.IsCurrentValueValid())
                {
                    this.PerformKeyboardSelection(selectionStart + selectionLength);
                    e.Handled = true;
                }
                _fireSelectionChangedEvent = false;
                break;

            case Key.Left:
                if (this.IsCurrentValueValid())
                {
                    this.PerformKeyboardSelection(selectionStart > 0 ? selectionStart - 1 : 0);
                    e.Handled = true;
                }
                _fireSelectionChangedEvent = false;
                break;

            default:
            {
                _fireSelectionChangedEvent = false;
                break;
            }
            }

            base.OnPreviewKeyDown(e);
        }
        private static bool IsComponentBound(FrameworkElement element, DependencyProperty property)
        {
            BindingExpression expression = BindingOperations.GetBindingExpression(element, property);

            return(expression != null);
        }
        /// <summary>
        /// Parse metadata from a target FrameworkElement.  This will cache the metadata on the element as an attached property.
        /// </summary>
        /// <param name="element">The target FrameworkElement to pull metadata from.</param>
        /// <param name="forceUpdate">If set, will not pull metadata from cache.</param>
        /// <param name="entity">The entity used.</param>
        /// <param name="bindingExpression">The bindingExpression used.</param>
        /// <returns>Returns the metadata associated with the element.  Will be null if no metadata was found.</returns>
        internal static ValidationMetadata ParseMetadata(FrameworkElement element, bool forceUpdate, out object entity, out BindingExpression bindingExpression)
        {
            entity            = null;
            bindingExpression = null;
            if (element == null)
            {
                return(null);
            }

            if (!forceUpdate)
            {
                ValidationMetadata existingVMD = element.GetValue(ValidationMetadataProperty) as ValidationMetadata;
                if (existingVMD != null)
                {
                    return(existingVMD);
                }
            }

            BindingExpression be = null;

            FieldInfo[] fields = element.GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType == typeof(DependencyProperty))
                {
                    // Found a dependency property
                    be = element.GetBindingExpression((DependencyProperty)field.GetValue(null));
                    if (be != null && be.ParentBinding != null && be.ParentBinding.Path != null)
                    {
                        // Found a BindingExpression, ensure it has valid data
                        entity = be.DataItem != null ? be.DataItem : element.DataContext;
                        if (entity != null)
                        {
                            if (be.ParentBinding.Mode == BindingMode.TwoWay)
                            {
                                bindingExpression = be;
                                // A twoway binding will be automatically chosen and the rest ignored
                                break;
                            }

                            // Perform an arbitrary sort on path (string), so the same dependency property is chosen consistently.
                            // Reflection ordering is not deterministic and if we just pick the first, we could be
                            // matched with different dependency properties depending on the run.
                            if (bindingExpression == null || string.Compare(be.ParentBinding.Path.Path, bindingExpression.ParentBinding.Path.Path, StringComparison.Ordinal) < 0)
                            {
                                bindingExpression = be;
                            }
                        }
                    }
                }
            }
            if (bindingExpression != null)
            {
                ValidationMetadata newVMD = ParseMetadata(bindingExpression.ParentBinding.Path.Path, entity);
                element.SetValue(ValidationMetadataProperty, newVMD);
                return(newVMD);
            }
            return(null);
        }
        public void ChangeValue(object sender, MouseButtonEventArgs e)
        {
            BindingExpression be = BindingOperations.GetBindingExpression((FrameworkElement)sender, ((DependencyProperty)Image.SourceProperty));

            Extensions.SetNewValue <bool>(be.ParentBinding.Path.Path, this, false);
        }
Example #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BindingInfo"/> class
 /// with the specified BindingExpression, DependencyProperty and FrameworkElement.
 /// </summary>
 /// <param name="bindingExpression">BindingExpression</param>
 /// <param name="bindingTarget">BindingTarget</param>
 /// <param name="element">Element</param>
 public BindingInfo(BindingExpression bindingExpression, DependencyProperty bindingTarget, FrameworkElement element)
 {
     this.BindingExpression = bindingExpression;
     this.BindingTarget     = bindingTarget;
     this.Element           = element;
 }
Example #23
0
        public static void ExportDataGrid(object sender, List <ExcelHeader> headers)
        {
            DataGrid currentGrid = sender as DataGrid;

            if (currentGrid != null)
            {
                StringBuilder sbGridData  = new StringBuilder();
                List <string> listColumns = new List <string>();

                List <DataGridColumn> listVisibleDataGridColumns = new List <DataGridColumn>();

                List <string> listHeaders = new List <string>();

                Microsoft.Office.Interop.Excel.Application application = null;

                Workbook workbook = null;

                Worksheet worksheet = null;

                int rowCount = headers.Count + 3;

                int colCount = 1;

                try
                {
                    application = new Microsoft.Office.Interop.Excel.Application();
                    workbook    = application.Workbooks.Add(Type.Missing);
                    worksheet   = (Worksheet)workbook.Worksheets[1];
                    for (int i = 1; i <= headers.Count; i++)
                    {
                        worksheet.Cells[i, 1] = headers[i - 1].Header;
                        var xlHeader = worksheet.get_Range("A" + i.ToString(), getColName(currentGrid.Columns.Count) + "1");
                        xlHeader.Merge(true);
                        xlHeader.Font.Size           = headers[i - 1].FontSize;
                        xlHeader.Font.Bold           = headers[i - 1].IsBold;
                        xlHeader.HorizontalAlignment = headers[i - 1].HorizontalAllignment;
                    }

                    if (currentGrid.HeadersVisibility == DataGridHeadersVisibility.Column || currentGrid.HeadersVisibility == DataGridHeadersVisibility.All)
                    {
                        foreach (DataGridColumn dataGridColumn in currentGrid.Columns.Where(dataGridColumn => dataGridColumn.Visibility == Visibility.Visible))
                        {
                            listVisibleDataGridColumns.Add(dataGridColumn);
                            if (dataGridColumn.Header != null)
                            {
                                listHeaders.Add(dataGridColumn.Header.ToString());
                            }
                            var dataHeader = worksheet.get_Range(getColName(colCount) + rowCount.ToString());
                            dataHeader.ColumnWidth              = dataGridColumn.Width.Value / 10;
                            dataHeader.HorizontalAlignment      = Microsoft.Office.Interop.Excel.Constants.xlCenter;
                            worksheet.Cells[rowCount, colCount] = dataGridColumn.Header;
                            var border = dataHeader.Borders;
                            border[XlBordersIndex.xlEdgeLeft].LineStyle   = XlLineStyle.xlContinuous;
                            border[XlBordersIndex.xlEdgeTop].LineStyle    = XlLineStyle.xlContinuous;
                            border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
                            border[XlBordersIndex.xlEdgeRight].LineStyle  = XlLineStyle.xlContinuous;
                            dataHeader.EntireColumn.NumberFormat          = "@";
                            colCount++;
                        }
                        foreach (object data in currentGrid.ItemsSource)
                        {
                            listColumns.Clear();
                            colCount = 1;
                            rowCount++;
                            foreach (DataGridColumn dataGridColumn in listVisibleDataGridColumns)
                            {
                                string              strValue            = string.Empty;
                                Binding             objBinding          = null;
                                double              ColWidth            = dataGridColumn.Width.Value;
                                DataGridBoundColumn dataGridBoundColumn = dataGridColumn as DataGridBoundColumn;

                                if (dataGridBoundColumn != null)
                                {
                                    objBinding = dataGridBoundColumn.Binding as Binding;
                                }

                                DataGridTemplateColumn dataGridTemplateColumn = dataGridColumn as DataGridTemplateColumn;

                                if (dataGridTemplateColumn != null)
                                {
                                    // This is a template column...let us see the underlying dependency object

                                    DependencyObject dependencyObject = dataGridTemplateColumn.CellTemplate.LoadContent();

                                    FrameworkElement frameworkElement = dependencyObject as FrameworkElement;
                                    if (frameworkElement != null)
                                    {
                                        FieldInfo fieldInfo = frameworkElement.GetType().GetField("ContentProperty", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                                        if (fieldInfo == null)
                                        {
                                            if (frameworkElement is System.Windows.Controls.TextBox || frameworkElement is TextBlock || frameworkElement is ComboBox)
                                            {
                                                fieldInfo = frameworkElement.GetType().GetField("TextProperty");
                                            }
                                            else if (frameworkElement is DatePicker)
                                            {
                                                fieldInfo = frameworkElement.GetType().GetField("SelectedDateProperty");
                                            }
                                        }

                                        if (fieldInfo != null)
                                        {
                                            DependencyProperty dependencyProperty = fieldInfo.GetValue(null) as DependencyProperty;
                                            if (dependencyProperty != null)
                                            {
                                                BindingExpression bindingExpression = frameworkElement.GetBindingExpression(dependencyProperty);
                                                if (bindingExpression != null)
                                                {
                                                    objBinding = bindingExpression.ParentBinding;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (objBinding != null)
                                {
                                    if (!String.IsNullOrEmpty(objBinding.Path.Path))
                                    {
                                        PropertyInfo pi;
                                        if (objBinding.Path.Path.Contains('.'))
                                        {
                                            pi = data.GetType().GetProperty(objBinding.Path.Path.Split('.')[0]);
                                            if (pi != null)
                                            {
                                                object propValue = pi.GetValue(data, null);

                                                pi = propValue.GetType().GetProperty(objBinding.Path.Path.Split('.')[1]);

                                                propValue = pi.GetValue(propValue, null);
                                                if (propValue != null)
                                                {
                                                    if (string.IsNullOrEmpty(objBinding.StringFormat))
                                                    {
                                                        strValue = Convert.ToString(propValue);
                                                    }
                                                    else
                                                    {
                                                        if (propValue.GetType() == typeof(DateTime))
                                                        {
                                                            strValue = (propValue as DateTime?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                        if (propValue.GetType() == typeof(TimeSpan))
                                                        {
                                                            strValue = (propValue as TimeSpan?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                        else if (propValue.GetType() == typeof(decimal) || propValue.GetType() == typeof(double))
                                                        {
                                                            strValue = (propValue as decimal?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                    }
                                                }

                                                else
                                                {
                                                    strValue = string.Empty;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            pi = data.GetType().GetProperty(objBinding.Path.Path);
                                            if (pi != null)
                                            {
                                                object propValue = pi.GetValue(data, null);
                                                if (propValue != null)
                                                {
                                                    if (string.IsNullOrEmpty(objBinding.StringFormat))
                                                    {
                                                        strValue = Convert.ToString(propValue);
                                                    }
                                                    else
                                                    {
                                                        if (propValue.GetType() == typeof(DateTime))
                                                        {
                                                            strValue = (propValue as DateTime?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                        if (propValue.GetType() == typeof(TimeSpan))
                                                        {
                                                            strValue = (propValue as TimeSpan?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                        else if (propValue.GetType() == typeof(decimal) || propValue.GetType() == typeof(double))
                                                        {
                                                            strValue = (propValue as decimal?).Value.ToString(objBinding.StringFormat);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    strValue = string.Empty;
                                                }
                                            }
                                        }
                                    }

                                    if (objBinding.Converter != null)
                                    {
                                        if (!String.IsNullOrEmpty(strValue))
                                        {
                                            strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                        }

                                        else
                                        {
                                            strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                        }
                                    }
                                }

                                listColumns.Add(strValue);

                                var border = worksheet.get_Range(getColName(colCount) + rowCount.ToString()).Borders;
                                border[XlBordersIndex.xlEdgeLeft].LineStyle   = XlLineStyle.xlContinuous;
                                border[XlBordersIndex.xlEdgeTop].LineStyle    = XlLineStyle.xlContinuous;
                                border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
                                border[XlBordersIndex.xlEdgeRight].LineStyle  = XlLineStyle.xlContinuous;
                                worksheet.Cells[rowCount, colCount]           = strValue;

                                colCount++;
                            }
                        }
                    }
                }

                catch (System.Runtime.InteropServices.COMException)
                {
                }

                finally
                {
                    application.Visible = true;
                    //workbook.PrintPreview(false);
                    //workbook.Close();
                    //application.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
                }
            }
        }
Example #24
0
        private void btnUpdateSource_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression binding = txtWindowTitle.GetBindingExpression(TextBox.TextProperty);

            binding.UpdateSource();
        }
        private string getValuePropertyBindingPath(DataGridColumn column)
        {
            string path = String.Empty;

            if (column is DataGridBoundColumn)
            {
                DataGridBoundColumn bc = column as DataGridBoundColumn;
                // VIKRAM: Added support for MultiBindings
                if (bc.Binding is Binding)
                {
                    path = (bc.Binding as Binding).Path.Path;
                }
                else
                {
                    // assume Multibinding with data as the first binding
                    path = ((bc.Binding as MultiBinding).Bindings[0] as Binding).Path.Path;
                }
                // END VIKRAM
            }
            else if (column is DataGridTemplateColumn)
            {
                DataGridTemplateColumn tc = column as DataGridTemplateColumn;

                object templateContent = tc.CellTemplate.LoadContent();

                if (templateContent != null && templateContent is TextBlock)
                {
                    TextBlock block = templateContent as TextBlock;

                    BindingExpression binding = block.GetBindingExpression(TextBlock.TextProperty);

                    path = binding.ParentBinding.Path.Path;
                }
            }
            else if (column is DataGridComboBoxColumn)
            {
                DataGridComboBoxColumn comboColumn = column as DataGridComboBoxColumn;

                path = null;

                Binding binding = ((comboColumn.SelectedValueBinding) as Binding);

                if (binding == null)
                {
                    binding = ((comboColumn.SelectedItemBinding) as Binding);
                }

                if (binding == null)
                {
                    binding = comboColumn.SelectedValueBinding as Binding;
                }

                if (binding != null)
                {
                    path = binding.Path.Path;
                }

                if (comboColumn.SelectedItemBinding != null && comboColumn.SelectedValueBinding == null)
                {
                    if (path != null && path.Trim().Length > 0)
                    {
                        if (DataGridComboBoxExtensions.GetIsTextFilter(comboColumn))
                        {
                            path += "." + comboColumn.DisplayMemberPath;
                        }
                        else
                        {
                            path += "." + comboColumn.SelectedValuePath;
                        }
                    }
                }
            }

            return(path);
        }
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            #region End
            if (Turn == 255)
            {
                MessageBox.Show("Finished!");
                return;
            }
            #endregion

            #region Turn variables
            ///<summary>
            ///Turn variable, Disk 1 turn variable and 3DPoint variables
            ///</summary>
            ++Turn;
            Disk1Turn = Disk1Turn * -1;

            Point3D point1 = new Point3D(x1, y1, z1);
            Point3D point2 = new Point3D(x2, y2, z2);
            Point3D point3 = new Point3D(x3, y3, z3);
            Point3D point4 = new Point3D(x4, y4, z4);
            Point3D point5 = new Point3D(x5, y5, z5);
            Point3D point6 = new Point3D(x6, y6, z6);
            Point3D point7 = new Point3D(x7, y7, z7);
            Point3D point8 = new Point3D(x8, y8, z8);
            #endregion

            #region First Turn
            if (Turn == 1)
            {
                list_X0.Add(point3);
                list_X0.Add(point4);
                list_X0.Add(point5);
                list_X0.Add(point6);
                list_X0.Add(point7);
                list_X0.Add(point8);
            }
            #endregion

            #region Disk 1
            if (Disk1Turn > 0)
            {
                x1++;
                if (x1 == 3)
                {
                    x1 = 0;
                }
                list_X0.Remove(point1);
                list_X1.Remove(point1);
                list_X2.Remove(point1);
                point1.X = x1;

                if (x1 == 0)
                {
                    if (list_X0.Count > 0)
                    {
                        y1 = list_X0.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y1 = 7;
                    }
                    point1.Y = y1;
                    list_X0.Add(point1);
                }
                else if (x1 == 1)
                {
                    if (list_X1.Count > 0)
                    {
                        y1 = list_X1.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y1 = 7;
                    }
                    point1.Y = y1;
                    list_X1.Add(point1);
                }
                else
                {
                    if (list_X2.Count > 0)
                    {
                        y1 = list_X2.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y1 = 7;
                    }
                    point1.Y = y1;
                    list_X2.Add(point1);
                }
                Grid.SetColumn(Disk1, x1);
                int yy1 = (int)y1;
                Grid.SetRow(Disk1, yy1);
            }

            #endregion

            #region Disk 2
            if ((Turn - 2) % 4 == 0 || Turn == 2)
            {
                list_X0.Remove(point2);
                list_X1.Remove(point2);
                list_X2.Remove(point2);
                x2 = x1 + 1;
                if (x2 == 3)
                {
                    x2 = 0;
                }
                point2.X = x2;
                if (x2 == 0)
                {
                    if (list_X0.Count > 0)
                    {
                        y2 = list_X0.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y2 = 7;
                    }
                    point2.Y = y2;
                    list_X0.Add(point2);
                }
                else if (x2 == 1)
                {
                    if (list_X1.Count > 0)
                    {
                        y2 = list_X1.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y2 = 7;
                    }
                    point2.Y = y2;
                    list_X1.Add(point2);
                }
                else
                {
                    if (list_X2.Count > 0)
                    {
                        y2 = list_X2.Min(y => y.Y) - 1;
                    }
                    else
                    {
                        y2 = 7;
                    }
                    point2.Y = y2;
                    list_X2.Add(point2);
                }
                Grid.SetColumn(Disk2, x2);
                int yy2 = (int)y2;
                Grid.SetRow(Disk2, yy2);
            }
            #endregion

            #region Other Disks
            if (Turn % 4 == 0)
            {
                #region Variables
                ///<sumarry>
                ///Variables to see wich disk should turn and from to wich pole it should turn
                ///Also calculates the vertical position as in if there are disks beneath the postion the disk goes to
                ///</sumarry>

                if (!list_X0.Contains(point1))
                {
                    if (list_X0.Any())
                    {
                        zx0 = list_X0.Min(z => z.Z);
                    }
                    else
                    {
                        zx0 = 9;
                    }
                }
                else
                {
                    zx0 = 10;
                }

                if (!list_X1.Contains(point1))
                {
                    if (list_X1.Any())
                    {
                        zx1 = list_X1.Min(z => z.Z);
                    }
                    else
                    {
                        zx1 = 9;
                    }
                }
                else
                {
                    zx1 = 10;
                }

                if (!list_X2.Contains(point1))
                {
                    if (list_X2.Any())
                    {
                        zx2 = list_X2.Min(z => z.Z);
                    }
                    else
                    {
                        zx2 = 9;
                    }
                }
                else
                {
                    zx2 = 10;
                }

                KleinsteZ = Math.Min(zx0, Math.Min(zx1, zx2));
                #endregion

                switch (KleinsteZ)
                {
                    #region Disk 3
                case 3:

                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point3);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x3 = 1;
                            if (zx1 != 9)
                            {
                                y3 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X1.Add(point3);
                        }
                        else
                        {
                            x3 = 2;
                            if (zx2 != 9)
                            {
                                y3 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X2.Add(point3);
                        }
                    }

                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point3);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x3 = 0;
                            if (zx0 != 9)
                            {
                                y3 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X0.Add(point3);
                        }
                        else
                        {
                            x3 = 2;
                            if (zx2 != 9)
                            {
                                y3 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X2.Add(point3);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point3);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x3 = 0;
                            if (zx0 != 9)
                            {
                                y3 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X0.Add(point3);
                        }
                        else
                        {
                            x3 = 1;
                            if (zx1 != 9)
                            {
                                y3 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y3 = 7;
                            }

                            point3.X = x3;
                            point3.Y = y3;
                            list_X1.Add(point3);
                        }
                    }
                    Grid.SetColumn(Disk3, x3);
                    int yy3 = (int)y3;
                    Grid.SetRow(Disk3, yy3);
                    break;

                    #endregion
                    #region Disk 4
                case 4:
                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point4);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x4 = 1;
                            if (zx1 != 9)
                            {
                                y4 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X1.Add(point4);
                        }
                        else
                        {
                            x4 = 2;
                            if (zx2 != 9)
                            {
                                y4 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X2.Add(point4);
                        }
                    }
                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point4);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x4 = 0;
                            if (zx0 != 9)
                            {
                                y4 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X0.Add(point4);
                        }
                        else
                        {
                            x4 = 2;
                            if (zx2 != 9)
                            {
                                y4 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X2.Add(point4);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point4);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x4 = 0;
                            if (zx0 != 9)
                            {
                                y4 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X0.Add(point4);
                        }
                        else
                        {
                            x4 = 1;
                            if (zx1 != 9)
                            {
                                y4 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y4 = 7;
                            }

                            point4.X = x4;
                            point4.Y = y4;
                            list_X1.Add(point4);
                        }
                    }

                    Grid.SetColumn(Disk4, x4);
                    int yy4 = (int)y4;
                    Grid.SetRow(Disk4, yy4);
                    break;

                    #endregion
                    #region Disk 5
                case 5:
                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point5);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x5 = 1;
                            if (zx1 != 9)
                            {
                                y5 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X1.Add(point5);
                        }
                        else
                        {
                            x5 = 2;
                            if (zx2 != 9)
                            {
                                y5 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X2.Add(point5);
                        }
                    }
                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point5);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x5 = 0;
                            if (zx0 != 9)
                            {
                                y5 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X0.Add(point5);
                        }
                        else
                        {
                            x5 = 2;
                            if (zx2 != 9)
                            {
                                y5 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X2.Add(point5);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point5);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x5 = 0;
                            if (zx0 != 9)
                            {
                                y5 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X0.Add(point5);
                        }
                        else
                        {
                            x5 = 1;
                            if (zx1 != 9)
                            {
                                y5 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y5 = 7;
                            }

                            point5.X = x5;
                            point5.Y = y5;
                            list_X1.Add(point5);
                        }
                    }

                    Grid.SetColumn(Disk5, x5);
                    int yy5 = (int)y5;
                    Grid.SetRow(Disk5, yy5);
                    break;

                    #endregion
                    #region Disk 6
                case 6:
                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point6);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x6 = 1;
                            if (zx1 != 9)
                            {
                                y6 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X1.Add(point6);
                        }
                        else
                        {
                            x6 = 2;
                            if (zx2 != 9)
                            {
                                y6 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X2.Add(point6);
                        }
                    }
                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point6);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x6 = 0;
                            if (zx0 != 9)
                            {
                                y6 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X0.Add(point6);
                        }
                        else
                        {
                            x6 = 2;
                            if (zx2 != 9)
                            {
                                y6 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X2.Add(point6);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point6);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x6 = 0;
                            if (zx0 != 9)
                            {
                                y6 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X0.Add(point6);
                        }
                        else
                        {
                            x6 = 1;
                            if (zx1 != 9)
                            {
                                y6 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y6 = 7;
                            }

                            point6.X = x6;
                            point6.Y = y6;
                            list_X1.Add(point6);
                        }
                    }

                    Grid.SetColumn(Disk6, x6);
                    int yy6 = (int)y6;
                    Grid.SetRow(Disk6, yy6);
                    break;

                    #endregion
                    #region Disk 7
                case 7:
                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point7);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x7 = 1;
                            if (zx1 != 9)
                            {
                                y7 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X1.Add(point7);
                        }
                        else
                        {
                            x7 = 2;
                            if (zx2 != 9)
                            {
                                y7 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X2.Add(point7);
                        }
                    }
                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point7);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x7 = 0;
                            if (zx0 != 9)
                            {
                                y7 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X0.Add(point7);
                        }
                        else
                        {
                            x7 = 2;
                            if (zx2 != 9)
                            {
                                y7 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X2.Add(point7);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point7);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x7 = 0;
                            if (zx0 != 9)
                            {
                                y7 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X0.Add(point7);
                        }
                        else
                        {
                            x7 = 1;
                            if (zx1 != 9)
                            {
                                y7 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y7 = 7;
                            }

                            point7.X = x7;
                            point7.Y = y7;
                            list_X1.Add(point7);
                        }
                    }

                    Grid.SetColumn(Disk7, x7);
                    int yy7 = (int)y7;
                    Grid.SetRow(Disk7, yy7);
                    break;

                    #endregion
                    #region Disk 8
                case 8:
                    if (zx0 == KleinsteZ)
                    {
                        list_X0.Remove(point8);
                        if (Math.Min(zx1, zx2) == zx1)
                        {
                            x8 = 1;
                            if (zx1 != 9)
                            {
                                y8 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X1.Add(point8);
                        }
                        else
                        {
                            x8 = 2;
                            if (zx2 != 9)
                            {
                                y8 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X2.Add(point8);
                        }
                    }
                    else if (zx1 == KleinsteZ)
                    {
                        list_X1.Remove(point8);
                        if (Math.Min(zx0, zx2) == zx0)
                        {
                            x8 = 0;
                            if (zx0 != 9)
                            {
                                y8 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X0.Add(point8);
                        }
                        else
                        {
                            x8 = 2;
                            if (zx2 != 9)
                            {
                                y8 = list_X2.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X2.Add(point8);
                        }
                    }
                    else
                    {
                        list_X2.Remove(point8);
                        if (Math.Min(zx0, zx1) == zx0)
                        {
                            x8 = 0;
                            if (zx0 != 9)
                            {
                                y8 = list_X0.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X0.Add(point8);
                        }
                        else
                        {
                            x8 = 1;
                            if (zx1 != 9)
                            {
                                y8 = list_X1.Min(y => y.Y) - 1;
                            }
                            else
                            {
                                y8 = 7;
                            }

                            point8.X = x8;
                            point8.Y = y8;
                            list_X1.Add(point8);
                        }
                    }

                    Grid.SetColumn(Disk8, x8);
                    int yy8 = (int)y8;
                    Grid.SetRow(Disk8, yy8);
                    break;
                    #endregion
                }
            }
            #endregion

            #region Show turn at label
            BindingExpression be = Turn_count.GetBindingExpression(TextBox.TextProperty);
            Turn_count.Text = Turn.ToString();
            be.UpdateSource();
            #endregion
        }
Example #27
0
 public override bool MustNotify(object dataSource, object source, PropertyChangedEventArgs args)
 {
     return(source == dataSource && BindingExpression.Equals(args.PropertyName));
 }
Example #28
0
        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            BindingExpression be = ((TextBox)sender).GetBindingExpression(TextBox.TextProperty);

            be.UpdateSource();
        }
Example #29
0
 private void OnLoaded(object sender, RoutedEventArgs e)
 {
     _textBinding = searchBox.GetBindingExpression(TextBox.TextProperty);
     searchBox.Focus();
 }
        public void SearchValidationsRecursive(DependencyObject depObj)
        {
            if (depObj != null)
            {
                int depObjCount = VisualTreeHelper.GetChildrenCount(depObj);
                for (int i = 0; i < depObjCount; i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null)
                    {
                        //.NET Controls Validation
                        BindingExpression bindingExpression = null;
                        if (child is TextBox)
                        {
                            TextBox textBox = (TextBox)child;
                            bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
                        }
                        else if (child is ComboBox)
                        {
                            ComboBox comboBox = (ComboBox)child;
                            bindingExpression = comboBox.GetBindingExpression(ComboBox.SelectedValueProperty);
                            if (bindingExpression == null)
                            {
                                bindingExpression = comboBox.GetBindingExpression(ComboBox.TextProperty);
                            }
                        }
                        else if (child is Ginger.Agents.ucAgentControl)
                        {
                            Ginger.Agents.ucAgentControl agentControl = (Ginger.Agents.ucAgentControl)child;
                            bindingExpression = agentControl.GetBindingExpression(Ginger.Agents.ucAgentControl.SelectedAgentProperty);
                        }

                        if (bindingExpression != null)
                        {
                            // do if there is validation bindingExpression.
                            bindingExpression.UpdateSource();

                            if (bindingExpression.HasValidationError)
                            {
                                errorsFound = true;
                            }
                        }

                        //Custom controls Validations
                        if (errorsFound == false)
                        {
                            if (child is ucGrid)
                            {
                                errorsFound = ((ucGrid)child).HasValidationError();
                            }
                            else if (child is UCTreeView)
                            {
                                errorsFound = ((UCTreeView)child).HasValidationError();
                            }
                        }
                    }

                    if (errorsFound == true)
                    {
                        return;
                    }
                    else
                    {
                        SearchValidationsRecursive(child);
                    }
                }
            }
        }
Example #31
0
 public MultiBinding()
 {
     Mode = BindingMode.OneWay;
     _bindingExpression = new BindingExpression(this, nameof(InternalValue.Value));
 }
Example #32
0
        internal static void RefreshBindingExpressionCommon(INTERNAL_PropertyStorage storage, BindingExpression expression)
        {
            global::System.Diagnostics.Debug.Assert(expression != null, "Expression should not be null");
            global::System.Diagnostics.Debug.Assert(storage.IsExpression || storage.IsExpressionFromStyle, "Property base value is not a BindingExpression !");

            UpdateEffectiveValue(storage,
                                 expression,
                                 expression.ParentBinding._isInStyle ? BaseValueSourceInternal.LocalStyle : BaseValueSourceInternal.Local,
                                 false, // coerceWithCurrentValue
                                 false, // coerceValue
                                 false, // clearValue
                                 true); // propagateChanges
        }
Example #33
0
 public void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
 {
     BindingExpression binding = ((TextBox) sender).GetBindingExpression(TextBox.TextProperty);
     if (binding != null)
         binding.UpdateSource();
 }
        void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            BindingExpression be = ((TextBox)this.AssociatedObject).GetBindingExpression(TextBox.TextProperty);

            be.UpdateSource();
        }
Example #35
0
        private static object EvaluateExpression(BindingExpression expression)
        {
            if (expression.ToString().Equals("{BaseUri}", StringComparison.OrdinalIgnoreCase))
            {
                return(CSMUrl);
            }

            var concat = expression as ConcatenatedBindingExpression;

            if (concat != null)
            {
                var strb = new StringBuilder();
                foreach (var item in concat.Expressions)
                {
                    strb.Append(EvaluateExpression(item));
                }
                return(strb.ToString());
            }

            var conditional = expression as ConditionalBindingExpression;

            if (conditional != null)
            {
                var strb = new StringBuilder();
                strb.Append('[');
                strb.Append(EvaluateExpression(conditional.ConcatenatedExpression));
                strb.Append(']');
                return(strb.ToString());
            }

            var literal = expression as LiteralBindingExpression;

            if (literal != null)
            {
                return(literal.Text);
            }

            var instance = expression as InstanceBindingExpression;

            if (instance != null)
            {
                return(instance.Context);
            }

            var property = expression as PropertyPathBindingExpression;

            if (property != null)
            {
                var obj = EvaluateExpression(property.Expression);
                if (obj == null)
                {
                    throw new InvalidOperationException(property.Expression + " expression should not be null");
                }

                var prop = obj.GetType().GetProperty(property.PropertyName);
                if (prop == null)
                {
                    return("{" + Char.ToLowerInvariant(property.PropertyName[0]) + property.PropertyName.Substring(1) + "}");
                }

                var value = prop.GetValue(obj);
                return(value);
            }

            var parameter = expression as ParameterBindingExpression;

            if (parameter != null)
            {
                var name = parameter.ToString().Split(new[] { '.', '{', '}' }, StringSplitOptions.RemoveEmptyEntries).Last();
                return("{" + Char.ToLowerInvariant(name[0]) + name.Substring(1) + "}");
            }

            var formatting = expression as FormattingBindingExpression;

            if (formatting != null)
            {
                return("{" + formatting.FormatString + "}");
            }

            throw new InvalidOperationException("Should not reach here. " + expression.GetType() + ", " + expression);
        }
Example #36
0
 public EventBinding(BindingExpression expression, object targetObject)
     : base(expression, targetObject)
 {
 }
Example #37
0
        public static ValidationMetadata ParseMetadata(FrameworkElement element, bool forceUpdate, out object entity, out BindingExpression bindingExpression)
        {
            entity            = null;
            bindingExpression = null;
            if (element == null)
            {
                return(null);
            }
            if (!forceUpdate)
            {
                var validationMetadata = element.GetValue(ValidationMetadataProperty) as ValidationMetadata;
                if (validationMetadata != null)
                {
                    return(validationMetadata);
                }
            }

            foreach (var field in element.GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy))
            {
                if (field.FieldType != typeof(DependencyProperty))
                {
                    continue;
                }

                var bindingExpression1 = element.GetBindingExpression((DependencyProperty)field.GetValue(null));

                if (bindingExpression1?.ParentBinding?.Path == null)
                {
                    continue;
                }

                entity = bindingExpression1.DataItem ?? element.DataContext;

                if (entity == null)
                {
                    continue;
                }

                if (bindingExpression1.ParentBinding.Mode == BindingMode.TwoWay)
                {
                    bindingExpression = bindingExpression1;
                    break;
                }

                if (bindingExpression == null || string.Compare(bindingExpression1.ParentBinding.Path.Path, bindingExpression.ParentBinding.Path.Path, StringComparison.Ordinal) < 0)
                {
                    bindingExpression = bindingExpression1;
                }
            }

            if (bindingExpression == null)
            {
                return(null);
            }

            var metadata = ParseMetadata(bindingExpression.ParentBinding.Path.Path, entity);

            element.SetValue(ValidationMetadataProperty, metadata);
            return(metadata);
        }
Example #38
0
        /// <summary>
        /// Returns a RegexValidationRule to be used for validating the specified TextBox.
        /// If the TextBox is not yet initialized, this method returns null.
        /// </summary>
        static RegexValidationRule GetRegexValidationRuleForTextBox(TextBox textBox)
        {
            if (!textBox.IsInitialized)
            {
                // If the TextBox.Text property is bound, but the TextBox is not yet
                // initialized, the property's binding can be null.  In that situation,
                // hook its Initialized event and verify the validation rule again when
                // that event fires.  At that point in time, the Text property's binding
                // will be non-null.
                EventHandler callback = null;
                callback = delegate
                {
                    textBox.Initialized -= callback;
                    VerifyRegexValidationRule(textBox);
                };
                textBox.Initialized += callback;
                return(null);
            }

            // Get the binding expression associated with the TextBox's Text property.
            BindingExpression expression = textBox.GetBindingExpression(TextBox.TextProperty);

            if (expression == null)
            {
                throw new InvalidOperationException(
                          "The TextBox's Text property must be bound for the RegexValidator to validate it.");
            }

            // Get the binding which owns the binding expression.
            Binding binding = expression.ParentBinding;

            if (binding == null)
            {
                throw new ApplicationException(
                          "Unexpected situation: the TextBox.Text binding expression has no parent binding.");
            }

            // Look for an existing instance of the RegexValidationRule class in the
            // binding.  If there is more than one instance in the ValidationRules
            // then throw an exception because we don't know which one to modify.
            RegexValidationRule regexRule = null;

            foreach (ValidationRule rule in binding.ValidationRules)
            {
                if (rule is RegexValidationRule)
                {
                    if (regexRule == null)
                    {
                        regexRule = rule as RegexValidationRule;
                    }
                    else
                    {
                        throw new InvalidOperationException(
                                  "There should not be more than one RegexValidationRule in a Binding's ValidationRules.");
                    }
                }
            }

            // If the TextBox.Text property's binding does not yet have an
            // instance of RegexValidationRule in its ValidationRules,
            // add an instance now and return it.
            if (regexRule == null)
            {
                regexRule = new RegexValidationRule();
                binding.ValidationRules.Add(regexRule);
            }

            return(regexRule);
        }
Example #39
0
 /// <summary>
 /// ビヘイビア登録
 /// </summary>
 protected override void OnAttached()
 {
     base.OnAttached();
     _Binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
 }
Example #40
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression be = ItemNameTextBox.GetBindingExpression(TextBox.TextProperty);

            be?.UpdateSource();
        }
Example #41
0
        Expression ParseAtom()
        {
            string id;
            Expression x = null;
            FunctionDefinition fnDef = null;

            switch (_token.Type)
            {
                // literals
                case TKTYPE.LITERAL:
                    x = new Expression(_token);
                    break;

                // identifiers
                case TKTYPE.IDENTIFIER:

                    // get identifier
                    id = (string)_token.Value;

                    // look for functions
                    if (_fnTbl.TryGetValue(id, out fnDef))
                    {
                        var p = GetParameters();
                        var pCnt = p == null ? 0 : p.Count;
                        if (fnDef.ParmMin != -1 && pCnt < fnDef.ParmMin)
                        {
                            Throw("Too few parameters.");
                        }
                        if (fnDef.ParmMax != -1 && pCnt > fnDef.ParmMax)
                        {
                            Throw("Too many parameters.");
                        }
                        x = new FunctionExpression(fnDef, p);
                        break;
                    }

                    // look for simple variables (much faster than binding!)
                    if (_vars.ContainsKey(id))
                    {
                        x = new VariableExpression(_vars, id);
                        break;
                    }

                    // look for external objects
                    var xObj = GetExternalObject(id);
                    if (xObj != null)
                    {
                        x = new XObjectExpression(xObj);
                        break;
                    }

                    // look for bindings
                    if (DataContext != null)
                    {
                        var list = new List<BindingInfo>();
                        for (var t = _token; t != null; t = GetMember())
                        {
                            list.Add(new BindingInfo((string)t.Value, GetParameters()));
                        }
                        x = new BindingExpression(this, list, _ci);
                        break;
                    }
                    Throw("Unexpected identifier");
                    break;

                // sub-expressions
                case TKTYPE.GROUP:

                    // anything other than opening parenthesis is illegal here
                    if (_token.ID != TKID.OPEN)
                    {
                        Throw("Expression expected.");
                    }

                    // get expression
                    GetToken();
                    x = ParseCompare();

                    // check that the parenthesis was closed
                    if (_token.ID != TKID.CLOSE)
                    {
                        Throw("Unbalanced parenthesis.");
                    }

                    break;
            }

            // make sure we got something...
            if (x == null)
            {
                Throw();
            }

            // done
            GetToken();
            return x;
        }
Example #42
0
        //------------------------------------------------------
        //
        //  Private Method
        //
        //------------------------------------------------------

        private object GetPreviousData(DependencyObject d)
        {
            // move up to the next containing DataContext scope
            for (; d != null; d = FrameworkElement.GetFrameworkParent(d))
            {
                if (BindingExpression.HasLocalDataContext(d))
                {
                    // special case:  if the element is a ContentPresenter
                    // whose templated parent is a ContentControl or
                    // HeaderedItemsControl, and both have the same
                    // DataContext, we'll use the parent instead of the
                    // ContentPresenter.  In this case, the DataContext
                    // of the CP is set by various forwarding rules, and
                    // shouldn't count as a new scope.
                    // Similarly, do the same for a FE whose parent
                    // is a GridViewRowPresenter;  this enables Previous bindings
                    // inside ListView.
                    FrameworkElement parent, child;
                    ContentPresenter cp;

                    if ((cp = d as ContentPresenter) != null)
                    {
                        child  = cp;
                        parent = cp.TemplatedParent as FrameworkElement;
                        if (!(parent is ContentControl || parent is HeaderedItemsControl))
                        {
                            parent = cp.Parent as System.Windows.Controls.Primitives.GridViewRowPresenterBase;
                        }
                    }
                    else
                    {
                        child  = d as FrameworkElement;
                        parent = ((child != null) ? child.Parent : null) as System.Windows.Controls.Primitives.GridViewRowPresenterBase;
                    }

                    if (child != null && parent != null &&
                        ItemsControl.EqualsEx(child.DataContext, parent.DataContext))
                    {
                        d = parent;
                        if (!BindingExpression.HasLocalDataContext(parent))
                        {
                            continue;
                        }
                    }

                    break;
                }
            }

            if (d == null)
            {
                return(DependencyProperty.UnsetValue);   // we fell off the tree
            }
            // this only makes sense within generated content.  If this
            // is the case, then d is now the wrapper element, its visual
            // parent is the layout element, and the layout's ItemsOwner
            // is the govening ItemsControl.
            Visual           v      = d as Visual;
            DependencyObject layout = (v != null) ? VisualTreeHelper.GetParent(v) : null;
            ItemsControl     ic     = ItemsControl.GetItemsOwner(layout);

            if (ic == null)
            {
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.RefPreviousNotInContext);
                }
                return(null);
            }

            // now look up the wrapper's previous sibling within the
            // layout's children collection
            Visual v2        = layout as Visual;
            int    count     = (v2 != null) ? v2.InternalVisualChildrenCount : 0;
            int    j         = -1;
            Visual prevChild = null;   //child at j-1th index

            if (count != 0)
            {
                j = IndexOf(v2, v, out prevChild);
            }
            if (j > 0)
            {
                d = prevChild;
            }
            else
            {
                d = null;
                if ((j < 0) && TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error, TraceData.RefNoWrapperInChildren);
                }
            }
            return(d);
        }
Example #43
0
        private static void EnumTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue == null || ((CustomComboBox)d).IsLoaded == false)
            {
                return;
            }

            if (!((Type)e.NewValue).IsEnum)
            {
                throw new ArgumentException("Parameter is not an Enumermated type", "EnumType");
            }

            var customComboBox = (CustomComboBox)d;

            customComboBox.ItemsSource = customComboBox.CreateEnumDispalyItems();
            if (customComboBox.IsEditable == false)
            {
                customComboBox.ItemTemplate = customComboBox.CreateItemTemplate();
            }
            else
            {
                customComboBox.DisplayMemberPath = "DisplayName";
            }

            IValueConverter converter = new CustomConverter((v, t, p, c) =>
            {
                if (v != null)
                {
                    return(customComboBox.enumValues[v]);
                }
                return(null);
            }, (v, t, p, c) =>
            {
                if (v != null)
                {
                    return(customComboBox.displayValues[v]);
                }
                return(null);
            });

            BindingExpression bindExpression = BindingOperations.GetBindingExpression(customComboBox, SelectedItemProperty);

            if (bindExpression != null && bindExpression.ResolvedSource != null)
            {
                var selectedItemType = bindExpression.ResolvedSource.GetType().GetProperty(bindExpression.ResolvedSourcePropertyName).PropertyType;

                if (customComboBox.IsNullable && selectedItemType.IsGenericType)
                {
                    selectedItemType = selectedItemType.GetGenericArguments()[0];
                }
                if (customComboBox.EnumType != selectedItemType && selectedItemType.IsAssignableFrom(customComboBox.EnumType) == false)
                {
                    throw new ArgumentException("EnumType and SelectedItem Type is not equal.", "EnumType");
                }

                Binding newBinding = bindExpression.ParentBinding.Clone();
                if (newBinding.Converter == null)
                {
                    newBinding.Converter = converter;
                }

                customComboBox.SetBinding(SelectedItemProperty, newBinding);
            }
        }
Example #44
0
		void ApplyInner(Element templatedParent, BindableObject bindableObject, BindableProperty targetProperty)
		{
			if (_expression == null && templatedParent != null)
				_expression = new BindingExpression(this, SelfPath);

			_expression?.Apply(templatedParent, bindableObject, targetProperty);
		}
Example #45
0
 public static DotvvmControl WithBinding(this DotvvmControl control, DotvvmProperty property, BindingExpression expression)
 {
     control.SetBinding(property, expression);
     return control;
 }
Example #46
0
        private void AddExpression(BindingExpression expression, object targetObject, string propertyPath)
        {
            if (string.IsNullOrEmpty(propertyPath))
            {
                //Add it here
                Bindings.Add(BindingFactory.Create(expression, targetObject));
            }
            else
            {
                string propertyName, otherPath;
                if (propertyPath.Contains("."))
                {
                    int index = propertyPath.IndexOf('.');
                    propertyName = propertyPath.Substring(0, index);
                    otherPath = propertyPath.Substring(index + 1);
                }
                else
                {
                    otherPath = "";
                    propertyName = propertyPath;
                }

                BindingNode child;
                if (Children.ContainsKey(propertyName))
                {
                    child = Children[propertyName];
                }
                else
                {
                    child = new BindingNode(propertyName);
                    Children.Add(child.PropertyName, child);
                }

                child.AddExpression(expression, targetObject, otherPath);
            }
        }
Example #47
0
 public void AddExpression(BindingExpression expression, object targetObject)
 {
     AddExpression(expression, targetObject, expression.SourcePath);
 }
Example #48
0
 public PropertyBinding(BindingExpression expression, object targetObject)
     : base(expression, targetObject)
 {
 }
Example #49
0
 object IExpressionBinder.GetValue( HtmlBindingContext context, BindingExpression expression )
 {
   return GetValue( context, expression );
 }