Ejemplo n.º 1
0
        protected virtual MultiBindingExpression BuildMultiBindingExpression(IServiceProvider serviceProvider,
                                                                             Binding binding, bool isCustom)
        {
            if (binding != null)
            {
                try
                {
                    BindingExpressionBase bExp = SetTheBinding(BindingTarget.DependencyObject, BindingTarget.DependencyProperty, binding);
                    string bType = isCustom ? "PropBag-Based" : "Standard";
                    System.Diagnostics.Debug.WriteLine($"CREATING {bType} BINDING from {binding.Path.Path} to {BindingTarget.PropertyName} on object: {BindingTarget.ObjectName}.");
                    System.Diagnostics.Debug.WriteLine("This binding is the one that our MultiValueConverter is using.");
                }
                catch
                {
                    // System.Diagnostics.Debug.WriteLine("Suppressed exception thrown when setting the binding during call to Provide Value.");
                    // Ignore the exception, we don't really need to set the binding.
                    // TODO: Is there anyway to avoid getting to here?
                    System.Diagnostics.Debug.WriteLine("Attempt to SetBinding failed: The MultiValueConverter will contain 0 child bindings.");
                    binding = null; // Set it to null, so that it will not be used.
                }
            }
            else
            {
                binding = null;
                System.Diagnostics.Debug.WriteLine("No Binding was created: The MultiValueConverter will contain 0 child bindings.");
            }

            BindingMode mode = binding?.Mode ?? BindingInfo.Mode;

            MultiBindingExpression exp = WrapBindingInMultiValueConverter(serviceProvider, binding, mode);

            return(exp);
        }
Ejemplo n.º 2
0
        private void chkIndependentProperties_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (var icon in icons)
            {
                switch (eltType)
                {
                case ShapeRepresents.Node:
                    gui.nodeIcons.BindTextDisplayProperties(icon);
                    break;

                case ShapeRepresents.Arc:
                    gui.arcIcons.BindTextDisplayProperties(icon);
                    break;

                case ShapeRepresents.HyperArc:
                    gui.hyperarcIcons.BindTextDisplayProperties(icon);
                    break;
                }
                MultiBindingExpression mbe = BindingOperations.GetMultiBindingExpression(icon,
                                                                                         IconShape.DisplayTextProperty);
                mbe.UpdateTarget();
            }
            expTextProperties.IsExpanded = false;
            expTextProperties.IsExpanded = false;
            chkShowNodeName.IsEnabled    = false;
            chkShowNodeLabels.IsEnabled  = false;
            sldDistance.IsEnabled        = false;
            sldFontSize.IsEnabled        = false;
            sldPosition.IsEnabled        = false;
        }
        private void RefreshMenuBinding()
        {
            MultiBindingExpression b = BindingOperations.GetMultiBindingExpression(_docContextMenu,
                                                                                   ContextMenu.ItemsSourceProperty);

            b.UpdateTarget();
        }
Ejemplo n.º 4
0
        private void Button_Click_UpdateSourceDownlink(object sender, RoutedEventArgs e)
        {
            MultiBindingExpression mbex = BindingOperations.GetMultiBindingExpression(SpinEdit_DirectChannel, SpinEdit.TextProperty);

            if (mbex != null)
            {
                mbex.UpdateSource();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Update the text when focus is lost.
        /// </summary>
        /// <param name="e">The event arguments.</param>
        protected override void  OnLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e)
        {
            MultiBindingExpression bindingExpression = BindingOperations.GetMultiBindingExpression(this, EnumTextBox.TextProperty);

            base.OnLostKeyboardFocus(e);

            // For some reason, the selection isn't getting cleared when we lose keyboard focus, so we force it here.
            this.SelectionLength = 0;

            // Make sure the display looks reflects the underlying values.
            bindingExpression.UpdateTarget();
        }
Ejemplo n.º 6
0
        private void PackageIconImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            var image = sender as Image;

            e.Handled = true; // don't repropagate the event
            MultiBindingExpression binding = BindingOperations.GetMultiBindingExpression(image, Image.SourceProperty);

            if (binding != null && binding.BindingExpressions.All((x) => x.Status != BindingStatus.Detached))
            {
                binding.UpdateTarget();
            }
        }
Ejemplo n.º 7
0
        private void Binding_TargetUpdated(object sender, DataTransferEventArgs e)
        {
            string txt = TestTextBox.Text;

            mbindingExpression =
                BindingOperations.GetMultiBindingExpression(e.TargetObject, e.Property);
            mbindingExpression.UpdateSource();

            foreach (var bind in mbindingExpression.BindingExpressions)
            {
                bind.UpdateSource();
            }
        }
Ejemplo n.º 8
0
        protected virtual MultiBindingExpression ProvideStandardMultiBindingExp(IServiceProvider serviceProvider,
                                                                                BindingTarget bindingTarget, MyBindingInfo bInfo, Type sourceType)
        {
            // create wpf binding
            MyMultiValueConverter mValueConverter = new MyMultiValueConverter(BindingInfo.Mode);

            Binding binding = CreateDefaultBinding(bindingTarget, bInfo, sourceType, bInfo.PropertyPath);

            // This also sets the binding.
            MultiBindingExpression mExp = BuildMultiBindingExpression(serviceProvider, binding, isCustom: false);

            return(mExp);

            //// TODO: Should we SetTheBinding here? We need to test this.
            //return WrapBindingInMultiValueConverter(serviceProvider, binding, binding.Mode);
        }
Ejemplo n.º 9
0
        public static void UpdateTarget(this FrameworkElement element, DependencyProperty property)
        {
            BindingExpression expression = element.GetBindingExpression(property);

            if (expression != null)
            {
                expression.UpdateTarget( );
                return;
            }

            MultiBindingExpression multiExpression = BindingOperations.GetMultiBindingExpression(element, property);

            if (multiExpression != null)
            {
                multiExpression.UpdateTarget( );
            }
        }
Ejemplo n.º 10
0
        public bool Validate(object rootElement)
        {
            if (!(rootElement is UIElement))
            {
                return(false);
            }

            bool result = true; // initially no validation errors

            var textBoxes = GetVisualChilds <TextBox>(rootElement as UIElement);

            foreach (var t in textBoxes)
            {
                BindingExpression expression = t.GetBindingExpression(TextBox.TextProperty);
                if (expression != null)
                {
                    expression.UpdateSource();
                    result &= !Validation.GetHasError(t);
                }
                else
                {
                    MultiBindingExpression multiExpression =
                        BindingOperations.GetMultiBindingExpression(t, TextBox.TextProperty);

                    if (multiExpression != null)
                    {
                        multiExpression.UpdateSource();
                        result &= !Validation.GetHasError(t);
                    }
                }
            }

            var comboBoxes = GetVisualChilds <ComboBox>(rootElement as UIElement);

            foreach (var c in comboBoxes)
            {
                BindingExpression expression = c.GetBindingExpression(ComboBox.SelectedItemProperty);
                if (expression != null)
                {
                    expression.UpdateSource();
                    result &= !Validation.GetHasError(c);
                }
            }

            return(result);
        }
Ejemplo n.º 11
0
        protected virtual MultiBindingExpression WrapBindingInMultiValueConverter(IServiceProvider serviceProvider,
                                                                                  Binding binding, BindingMode mode)
        {
            // create wpf binding

            MyMultiValueConverter mValueConverter = new MyMultiValueConverter(mode);

            if (binding != null)
            {
                mValueConverter.Add(binding);
            }

            // return the expression provided by the multi-binding
            MultiBindingExpression exp = mValueConverter.GetMultiBindingExpression(serviceProvider);

            return(exp);
        }
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(MarkupExtension))
            {
                BindingExpression bindingExpression = value as BindingExpression;
                if (bindingExpression != null)
                {
                    return(bindingExpression.ParentBinding);
                }
                MultiBindingExpression multiBindingExpression = value as MultiBindingExpression;
                if (multiBindingExpression != null)
                {
                    return(multiBindingExpression.ParentMultiBinding);
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Ejemplo n.º 13
0
        private static void NavigateBindingExpressionTree(
            BindingExpressionBase bindingExpressionBase,
            Action <BindingExpression> action)
        {
            BindingExpression bindingExpression = bindingExpressionBase as BindingExpression;

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

            MultiBindingExpression multiBindingExpression = bindingExpressionBase as MultiBindingExpression;

            if (multiBindingExpression != null)
            {
                foreach (var subExpression in multiBindingExpression.BindingExpressions)
                {
                    NavigateBindingExpressionTree(subExpression, action);
                }
                return;
            }

            PriorityBindingExpression priorityBindingExpression = bindingExpressionBase as PriorityBindingExpression;

            if (priorityBindingExpression != null)
            {
                foreach (var subExpression in priorityBindingExpression.BindingExpressions)
                {
                    NavigateBindingExpressionTree(subExpression, action);
                }
                return;
            }

            throw new InvalidOperationException(
                      string.Format(
                          CultureInfo.CurrentCulture,
                          Resources.ExceptionUnexpectedBindingExpression,
                          bindingExpression.GetType().Name));
        }
Ejemplo n.º 14
0
        private void Filter_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            MultiBindingExpression genres = BindingOperations.GetMultiBindingExpression(lstGenres, ListBox.ItemsSourceProperty);

            genres.UpdateTarget();

            MultiBindingExpression programs = BindingOperations.GetMultiBindingExpression(lstPrograms, ListBox.ItemsSourceProperty);

            programs.UpdateTarget();

            MultiBindingExpression series = BindingOperations.GetMultiBindingExpression(lstSeries, ListBox.ItemsSourceProperty);

            series.UpdateTarget();

            MultiBindingExpression videos = BindingOperations.GetMultiBindingExpression(mivVideos, MediaItemsView.MediaItemsProperty);

            videos.UpdateTarget();

            BindingExpression summary = lblSummary.GetBindingExpression(Label.ContentProperty);

            summary.UpdateTarget();
        }
Ejemplo n.º 15
0
        private void Filter_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            MultiBindingExpression genres = BindingOperations.GetMultiBindingExpression(lstGenres, ListBox.ItemsSourceProperty);

            genres.UpdateTarget();

            MultiBindingExpression artists = BindingOperations.GetMultiBindingExpression(lstArtists, ListBox.ItemsSourceProperty);

            artists.UpdateTarget();

            MultiBindingExpression albums = BindingOperations.GetMultiBindingExpression(lstAlbums, ListBox.ItemsSourceProperty);

            albums.UpdateTarget();

            MultiBindingExpression songs = BindingOperations.GetMultiBindingExpression(mivSongs, MediaItemsView.MediaItemsProperty);

            songs.UpdateTarget();

            BindingExpression summary = lblSummary.GetBindingExpression(Label.ContentProperty);

            summary.UpdateTarget();
        }
        public static bool CheckAllValidationErrors(DependencyObject dependencyObject, DependencyProperty dependencyProperty)
        {
            bool isValid = true;

            if (BindingOperations.IsDataBound(dependencyObject, dependencyProperty))
            {
                Binding      binding      = BindingOperations.GetBinding(dependencyObject, dependencyProperty);
                MultiBinding multiBinding = null;
                if (binding == null)
                {
                    multiBinding = BindingOperations.GetMultiBinding(dependencyObject, dependencyProperty);
                    if (multiBinding == null)
                    {
                        return(true);
                    }
                }

                if (binding != null && binding.ValidationRules.Count > 0
                    ||
                    multiBinding != null && multiBinding.ValidationRules.Count > 0)
                {
                    BindingExpression      bindingExpression      = BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty);
                    MultiBindingExpression multiBindingExpression = null;
                    if (bindingExpression == null)
                    {
                        multiBindingExpression = BindingOperations.GetMultiBindingExpression(dependencyObject, dependencyProperty);
                        if (multiBindingExpression == null)
                        {
                            return(true);
                        }
                    }

                    BindingExpressionBase expression = bindingExpression ?? (BindingExpressionBase)multiBindingExpression;

                    switch (binding != null ? binding.Mode : multiBinding.Mode)
                    {
                    case BindingMode.OneTime:
                    case BindingMode.OneWay:
                        expression.UpdateTarget();
                        break;

                    default:
                        expression.UpdateSource();
                        break;
                    }

                    if (expression.HasError)
                    {
                        isValid = false;
                    }
                }


                // Another method:
                foreach (ValidationRule rule in (binding != null ? binding.ValidationRules : multiBinding.ValidationRules))
                {
                    ValidationResult result = rule.Validate(dependencyObject.GetValue(dependencyProperty), null);
                    if (!result.IsValid)
                    {
                        BindingExpression      bindingExpression      = BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty);
                        MultiBindingExpression multiBindingExpression = null;
                        if (bindingExpression == null)
                        {
                            multiBindingExpression = BindingOperations.GetMultiBindingExpression(dependencyObject, dependencyProperty);
                            if (multiBindingExpression == null)
                            {
                                continue;
                            }
                        }

                        BindingExpressionBase expression = bindingExpression ?? (BindingExpressionBase)multiBindingExpression;

                        System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
                        isValid = false;
                    }
                }
            }

            return(isValid);
        }
        /// <summary>
        /// Refreshes the bindings to the data grid item source
        /// </summary>
        private void RefreshItemBinding()
        {
            MultiBindingExpression mbe = BindingOperations.GetMultiBindingExpression(dgPartsToOrganise, DataGrid.ItemsSourceProperty);

            mbe.UpdateTarget();
        }
Ejemplo n.º 18
0
        private bool TryGetInitialValue(DependencyObject depo, DependencyProperty dp, ref object value)
        {
            if (depo == null || dp == null)
            {
                return(false);
            }

            Binding b = BindingOperations.GetBinding(depo, dp);

            if (b == null)
            {
                MultiBinding mb = BindingOperations.GetMultiBinding(depo, dp);

                if (mb == null)
                {
                    return(false);
                }

                b = mb.Bindings[0] as Binding;
            }

            if (b == null || b.Path == null || string.IsNullOrEmpty(b.Path.Path))
            {
                return(false);
            }

            BindingExpression be = BindingOperations.GetBindingExpression(depo, dp);

            if (be == null)
            {
                MultiBindingExpression mbe = BindingOperations.GetMultiBindingExpression(depo, dp);

                if (mbe == null)
                {
                    return(false);
                }

                be = mbe.BindingExpressions[0] as BindingExpression;
            }

            if (be == null || be.DataItem == null)
            {
                return(false);
            }

            var dobj = be.DataItem as DataObj;

            if (dobj != null)
            {
                string prop = b.Path.Path.Replace("Model.", "");
                if (initialModel != null)
                {
                    var pi = initialModel.GetType().GetProperty(prop);
                    if (pi != null)
                    {
                        value = pi.GetValue(initialModel, null);
                        return(true);
                    }
                }
            }

            return(TryGetInitialValue(be.DataItem as DependencyObject, DispatcherHelper.GetDependencyProperty(be.DataItem.GetType(), b.Path.Path + "Property"), ref value));
        }
Ejemplo n.º 19
0
        /// <summary>Метод-прослушка изменения текста в <see cref="TextBox"/> в котором была создана привязка <see cref="BindToNumericExtension"/>.</summary>
        /// <param name="sender"><see cref="TextBox"/> в котором изменился текст.</param>
        /// <param name="e">Параметры события. Не используются.</param>
        private void TextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            // Извлечение TetxBox и привязки его свойства Text
            TextBox textBox = (TextBox)sender;
            MultiBindingExpression multiBindingExpression = BindingOperations.GetMultiBindingExpression(textBox, TextBox.TextProperty);

            // Если привязка - это не PrivateMulti, то отключается прослушка и выход из метода.
            if (!(multiBindingExpression?.ParentMultiBinding is PrivateMulti bindPriv))
            {
                textBox.TextChanged -= TextBoxTextChanged;
                // Очистка приисоединённого свойства.
                ClearTextBindingState(textBox);
                return;
            }

            // Получение состояния привязки
            TextBoxBindingState bindingState = GetBindingState(textBox);

            // Сохранить новый текст и параметры изменения
            UpdateTextBindingState(textBox, e.Changes);

            // Если изменение произошло по привязке - выйти из метода
            if (bindingState.TextChangeSource == PropertyChangeSourceEnum.Binding)
            {
                // Сброс состояния обновления по привязке.
                bindingState.TextChangeSource = PropertyChangeSourceEnum.NotBinding;

                return;
            }

            // Создание триггера обновления источника и обновления источника в нём,
            // запоминание состояния триггера
            bool triggerHasUpdated;

            using (var trigger = new SourceUpdateTrigger(textBox, TextBox.TextProperty))
            {
                // Обновление источника с флагом обновления из метода UpdateSource().
                bindingState.UpdateSourceState = UpdateSourceStateEnum.Called;
                multiBindingExpression.UpdateSource();

                // Запоминание состояния триггера.
                triggerHasUpdated = trigger.HasUpdated;
            }

            // Получение привязки к источнику.
            BindingExpressionBase bindingSource = multiBindingExpression.BindingExpressions[0];

            // Проверка триггера обновления источника
            if (triggerHasUpdated)
            {
                // Вызов обновления привязки к источнику для передачи нового значения.
                //bindingSource.UpdateSource();
            }
            // Если обновления не было - значит была ошибка конвертера
            // Для режима ввода "Только числа" надо вызвать ковертер.
            else if (!triggerHasUpdated && bindPriv.IsNumericOnly)
            {
                // Установка флага отменённого обновления.
                bindingState.UpdateSourceState = UpdateSourceStateEnum.CallCanceled;

                // Вызов обновления привязки от источника для обработки причины прерывания обновления.
                bindingSource.UpdateTarget();
            }

            // Сброс флага обновления из метода UpdateSource().
            bindingState.UpdateSourceState = UpdateSourceStateEnum.NotCalled;
        }