示例#1
0
        public static bool IsParentValid(DependencyObject parent)
        {
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    if (binding.ValidationRules.Count > 0)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        expression.UpdateSource();

                        if (expression.HasError)
                        {
                            valid = false;
                        }
                    }
                }
            }
            return(valid);
        }
示例#2
0
        private static void GetBindings(FrameworkElement root, List <Tuple <FrameworkElement, DependencyProperty, Binding> > value)
        {
            foreach (FrameworkElement element in LogicalTreeHelper.GetChildren(root).OfType <FrameworkElement>())
            {
                FieldInfo[] properties = element.GetType().GetFields(BindingFlags.Public | BindingFlags.GetProperty |
                                                                     BindingFlags.Static | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo field in properties)
                {
                    if (field.FieldType == typeof(DependencyProperty))
                    {
                        DependencyProperty dp = (DependencyProperty)field.GetValue(null);

                        BindingExpression bindingExpression = BindingOperations.GetBindingExpression(element, dp);
                        //bindingExpression.
                        if (BindingOperations.IsDataBound(element, dp))
                        {
                            var b = BindingOperations.GetBinding(element, dp);
                            if (b != null)
                            {
                                value.Add(new Tuple <FrameworkElement, DependencyProperty, Binding>(element,
                                                                                                    dp,
                                                                                                    b
                                                                                                    ));
                            }
                        }
                    }
                }
                GetBindings(element, value);
            }
        }
 /// <summary>
 /// Sets or unsets the inner binding regarding to the passed source element value.
 /// </summary>
 /// <param name="sourceElement">The binding source element that must be assessed.</param>
 private void ToggleBinding(object sourceElement)
 {
     if (TargetObject != null && TargetProperty != null && SourceType != null)
     {
         // If has binding while should not have, clear binding:
         var currentBinding = BindingOperations.GetBindingBase(TargetObject, TargetProperty);
         if (currentBinding != null && (sourceElement == null || SourceType == null ||
                                        sourceElement?.GetType() != SourceType && !sourceElement.GetType().GetTypeInfo().IsSubclassOf(SourceType)))
         {
             BindingOperations.ClearBinding(TargetObject, TargetProperty);
             if (BindingOperations.IsDataBound(TargetObject, TargetProperty))                     // clearing may fail happen when called from datatemplate
             {
                 BindingOperations.SetBinding(TargetObject, TargetProperty, selfPropertyBinding); // set set "null" value.
             }
             init_to_empty = true;
         }
         // If has no binding while should have, set binding:
         else if (sourceElement != null && (currentBinding == null || ((currentBinding as Binding)?.IsEquivalentTo(selfPropertyBinding) == true)) &&
                  (sourceElement.GetType() == SourceType || sourceElement.GetType().GetTypeInfo().IsSubclassOf(SourceType)))
         {
             BindingOperations.SetBinding(TargetObject, TargetProperty, innerBinding ?? InnerBinding);
             init_to_empty = false;
         }
     }
 }
示例#4
0
        private void HandleMouseInput(Point position)
        {
            if (IsReadOnly)
            {
                return;
            }

            if (position.X < 0)
            {
                Value = Minimum;
            }
            else if (position.X > RenderSize.Width)
            {
                Value = Maximum;
            }
            else
            {
                Value = Math.Round(Minimum + ((position.X / RenderSize.Width) * (Maximum - Minimum)), Precision);
            }

            if (!BindingOperations.IsDataBound(this, ValueProperty))
            {
                return;
            }

            var bindingExpression = BindingOperations.GetBindingExpression(this, ValueProperty);

            if (bindingExpression != null)
            {
                bindingExpression.UpdateTarget();
            }
        }
示例#5
0
        internal TabItem GetTabItem(int index)
        {
            if (BindingOperations.IsDataBound(this, ItemsSourceProperty))
            {
                IList list = ItemsSource as IList;
                if (list != null)
                {
                    return(this.ItemContainerGenerator.ContainerFromItem(list[index]) as TabItem);
                }

                // ItemsSource is at least an IEnumerable
                int         i          = 0;
                IEnumerator enumerator = ItemsSource.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (i == index)
                    {
                        return(this.ItemContainerGenerator.ContainerFromItem(enumerator.Current) as TabItem);
                    }
                    i++;
                }
                return(null);
            }
            return(Items[index] as TabItem);
        }
        /// <summary>
        /// Метод, който визуализира цвета при неправилно въведени данни
        /// </summary>
        private void BeginInvalidInputAnimation()
        {
            ColorAnimation animation = new ColorAnimation(this.AnimationBrushColor, TimeSpan.FromSeconds(0.1))
            {
                AutoReverse       = true,
                FillBehavior      = FillBehavior.Stop,
                DecelerationRatio = 0.8
            };

            // Ако свойството за Background участва в Binding, няма да може да бъде анимирано, затова временно
            // откачаме Binding-а и го възстановяваме след края на анимацията (в метода storyBoard_Completed())
            if (BindingOperations.IsDataBound(this.AssociatedTextBox, Control.BackgroundProperty))
            {
                this.animatedPropertyBinding      = BindingOperations.GetBinding(this.AssociatedTextBox, Control.BackgroundProperty);
                this.animatedPropertyMultiBinding = BindingOperations.GetMultiBinding(this.AssociatedTextBox, Control.BackgroundProperty);

                if (this.animatedPropertyBinding != null || this.animatedPropertyMultiBinding != null)
                {
                    // задаваме текущата стойност локално
                    Brush currentValue = this.AssociatedObject.GetValue(Control.BackgroundProperty) as Brush;
                    this.AssociatedTextBox.Background = currentValue;
                }
            }

            Storyboard.SetTargetProperty(animation, new PropertyPath("(Control.Background).(SolidColorBrush.Color)"));
            Storyboard storyBoard = new Storyboard();

            storyBoard.Children.Add(animation);

            storyBoard.Completed += new EventHandler(StoryBoard_Completed);
            storyBoard.Begin(this.AssociatedTextBox);

            SystemSounds.Beep.Play();
        }
示例#7
0
        private static object CoerceMVVMHasError(DependencyObject dependencyObject, object baseValue)
        {
            bool hasError = (bool)baseValue;

            if (BindingOperations.IsDataBound(dependencyObject, MVVMHasErrorProperty))
            {
                if (GetHasErrorDescriptor(dependencyObject) == null)
                {
                    DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(Validation.HasErrorProperty, dependencyObject.GetType());
                    descriptor.AddValueChanged(dependencyObject, OnHasErrorChanged);
                    SetHasErrorDescriptor(dependencyObject, descriptor);
                    hasError = Validation.GetHasError(dependencyObject);
                }
            }
            else
            {
                if (GetHasErrorDescriptor(dependencyObject) != null)
                {
                    DependencyPropertyDescriptor descriptor = GetHasErrorDescriptor(dependencyObject);
                    descriptor.RemoveValueChanged(dependencyObject, OnHasErrorChanged);
                    SetHasErrorDescriptor(dependencyObject, null);
                }
            }

            return(hasError);
        }
示例#8
0
        /// <summary>
        /// Valida todos los controles de una ventana que se pase por parametro. Si existe algún error de validación se remarca
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static bool EsValido(DependencyObject parent)
        {
            bool valido = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule reglaValidacion in binding.ValidationRules)
                    {
                        ValidationResult result = reglaValidacion.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expresion = BindingOperations.GetBindingExpression(parent, entry.Property);
                            System.Windows.Controls.Validation.MarkInvalid(expresion, new ValidationError(reglaValidacion, expresion, result.ErrorContent, null));
                            valido = false;
                        }
                    }
                }
            }
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!EsValido(child))
                {
                    valido = false;
                }
            }
            return(valido);
        }
示例#9
0
        /// <summary> Устанавливает привязку данных для свойства к указанному Control </summary>
        private void SetBinding(PropertyInfo property, Control control, Panel panel)
        {
            IsVisibleIfAttribute isVisibleIfAttribute = property.GetAttribute <IsVisibleIfAttribute>();

            if (isVisibleIfAttribute != null)
            {
                Binding isVisibleBinding = new Binding(isVisibleIfAttribute.PropertyName);
                isVisibleBinding.ConverterParameter = isVisibleIfAttribute.ValueOfIsVisible;
                isVisibleBinding.Mode      = BindingMode.OneWay;
                isVisibleBinding.Converter = new ValueToVisibleConverter();
                BindingOperations.SetBinding(panel, Panel.VisibilityProperty, isVisibleBinding);
            }

            DependencyProperty dependencyProperty = this.GetDependencyProperty(property.PropertyType);

            if (!BindingOperations.IsDataBound(control, dependencyProperty))
            {
                Binding binding = new Binding(property.Name);
                if (property.PropertyType.Is <id>() || property.GetSetMethod() == null)
                {
                    binding.Mode = BindingMode.OneWay;
                }
                if (property.PropertyType.IsEnum)
                {
                    binding.Mode      = BindingMode.OneWay;                     //В другую сторону будет обрабатываться через код
                    binding.Converter = new EnumToIntConverter();
                }

                BindingOperations.SetBinding(control, dependencyProperty, binding);
            }
        }
示例#10
0
        internal int GetTabsCount()
        {
            if (BindingOperations.IsDataBound(this, ItemsSourceProperty))
            {
                IList list = ItemsSource as IList;
                if (list != null)
                {
                    return(list.Count);
                }

                // ItemsSource is only an IEnumerable.
                // Check the ItemsSource nullable to make sure the designer show it correctly.
                if (ItemsSource != null)
                {
                    int         i          = 0;
                    IEnumerator enumerator = ItemsSource.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        i++;
                    }
                    return(i);
                }
            }

            if (Items != null)
            {
                return(Items.Count);
            }

            return(0);
        }
        /// <summary>
        /// Gets control which represents quick access toolbar item
        /// </summary>
        /// <param name="element">Host control</param>
        /// <returns>Control which represents quick access toolbar item</returns>
        public static FrameworkElement?GetQuickAccessItem(UIElement element)
        {
            FrameworkElement?result = null;

            // If control supports the interface just return what it provides
            if (element is IQuickAccessItemProvider provider &&
                provider.CanAddToQuickAccessToolBar)
            {
                result = provider.CreateQuickAccessItem();
            }

            // The control isn't supported
            if (result is null)
            {
                throw new ArgumentException("The contol " + element.GetType().Name + " is not able to provide a quick access toolbar item");
            }

            RibbonProperties.SetIsElementInQuickAccessToolBar(result, true);

            if (BindingOperations.IsDataBound(result, UIElement.VisibilityProperty) == false)
            {
                RibbonControl.Bind(element, result, nameof(UIElement.Visibility), UIElement.VisibilityProperty, BindingMode.OneWay);
            }

            if (BindingOperations.IsDataBound(result, UIElement.IsEnabledProperty) == false)
            {
                RibbonControl.Bind(element, result, nameof(UIElement.IsEnabled), UIElement.IsEnabledProperty, BindingMode.OneWay);
            }

            return(result);
        }
        private static object CoerceHasError(DependencyObject d, Object baseValue)
        {
            var ret = (bool)baseValue;

            if (BindingOperations.IsDataBound(d, HasErrorProperty))
            {
                if (GetHasErrorDescriptor(d) == null)
                {
                    var desc = DependencyPropertyDescriptor.FromProperty(Validation.HasErrorProperty, d.GetType());
                    desc.AddValueChanged(d, OnHasErrorChanged);
                    SetHasErrorDescriptor(d, desc);
                    ret = Validation.GetHasError(d);
                }
            }
            else
            {
                if (GetHasErrorDescriptor(d) != null)
                {
                    var desc = GetHasErrorDescriptor(d);
                    desc.RemoveValueChanged(d, OnHasErrorChanged);
                    SetHasErrorDescriptor(d, null);
                }
            }

            return(ret);
        }
        private void ButtonOK_Click(object sender, RoutedEventArgs e)
        {
            //TODO make array and document types use this as well
            foreach (var ctrl in customControls)
            {
                var control = ctrl.EditControl;
                var values  = control.GetLocalValueEnumerator();
                while (values.MoveNext())
                {
                    var current = values.Current;
                    if (BindingOperations.IsDataBound(control, current.Property))
                    {
                        var binding = control.GetBindingExpression(current.Property);
                        if (binding.IsDirty)
                        {
                            binding.UpdateSource();
                        }
                    }
                }
            }

            if (documentReference != null)
            {
                documentReference.LiteDocument = currentDocument;
                documentReference.Collection.UpdateItem(documentReference);
            }

            DialogResult = true;
            Close();
        }
示例#14
0
        public static FrameworkElement GetQuickAccessItem(UIElement element)
        {
            FrameworkElement result = null;

            // If control supports the interface just return what it provides
            var provider = element as IQuickAccessItemProvider;

            if (provider != null &&
                provider.CanAddToQuickAccessToolBar)
            {
                result = ((IQuickAccessItemProvider)element).CreateQuickAccessItem();
            }

            // The control isn't supported
            if (result == null)
            {
                throw new ArgumentException("The contol " + element.GetType().Name + " is not able to provide a quick access toolbar item");
            }

            if (BindingOperations.IsDataBound(result, UIElement.VisibilityProperty) == false)
            {
                RibbonControl.Bind(element, result, "Visibility", UIElement.VisibilityProperty, BindingMode.OneWay);
            }

            if (BindingOperations.IsDataBound(result, UIElement.IsEnabledProperty) == false)
            {
                RibbonControl.Bind(element, result, "IsEnabled", UIElement.IsEnabledProperty, BindingMode.OneWay);
            }

            return(result);
        }
        void OnTaskCompleted(IProgressTask task)
        {
            switch (task.TaskNongeneric.Status)
            {
            case TaskStatus.RanToCompletion:
            {
                previousTask       = task;
                ProgressVisibility = Visibility.Collapsed;

                if (!BindingOperations.IsDataBound(contentPresenter, ContentPresenter.ContentProperty))
                {
                    contentPresenter.SetBinding(
                        ContentPresenter.ContentProperty,
                        new Binding("Child")
                        {
                            Source = this
                        }
                        );
                }

                childDataContext.Self = task.ResultNongeneric;
                break;
            }

            case TaskStatus.Faulted:
            case TaskStatus.Canceled:
                Task = previousTask;
                break;

            default:
                throw new InvalidOperationException();
            }
        }
示例#16
0
        //=====================================================================

        /// <summary>
        /// This is used to commit pending changes to the data source from
        /// a bound object and its children.
        /// </summary>
        /// <param name="parent">The parent object</param>
        public static void CommitChanges(this DependencyObject parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException(nameof(parent));
            }

            var localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                var entry = localValues.Current;

                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    var binding = BindingOperations.GetBindingExpression(parent, entry.Property);

                    if (binding != null)
                    {
                        binding.UpdateSource();
                    }
                }
            }

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                VisualTreeHelper.GetChild(parent, i).CommitChanges();
            }
        }
示例#17
0
        private static void dataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;

            if (dataGrid == null)
            {
                return;
            }

            if (BindingOperations.IsDataBound(dataGrid, DataGrid.ItemsSourceProperty))
            {
                Binding b = BindingOperations.GetBinding(dataGrid, DataGrid.ItemsSourceProperty);
                dataGrid.TargetUpdated += new EventHandler <DataTransferEventArgs>(dataGrid_TargetUpdated);

                string  xaml = XamlWriter.Save(b);
                Binding b2   = XamlReader.Parse(xaml) as Binding;
                if (b2 != null)
                {
                    b2.NotifyOnTargetUpdated = true;
                    BindingOperations.ClearBinding(dataGrid, DataGrid.ItemsSourceProperty);
                    BindingOperations.SetBinding(dataGrid, DataGrid.ItemsSourceProperty, b2);
                }
            }
            else
            {
                SetupColumnHeaders(dataGrid);
            }
        }
        internal TabItem GetTabItem(int index)
        {
            TabItem result;

            if (BindingOperations.IsDataBound(this, ItemsControl.ItemsSourceProperty))
            {
                IList list = base.ItemsSource as IList;
                if (list != null)
                {
                    result = (base.ItemContainerGenerator.ContainerFromItem(list[index]) as TabItem);
                }
                else
                {
                    int         i          = 0;
                    IEnumerator enumerator = base.ItemsSource.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        if (i == index)
                        {
                            result = (base.ItemContainerGenerator.ContainerFromItem(enumerator.Current) as TabItem);
                            return(result);
                        }
                        i++;
                    }
                    result = null;
                }
            }
            else
            {
                result = (base.Items[index] as TabItem);
            }
            return(result);
        }
示例#19
0
        internal int GetTabsCount()
        {
            if (BindingOperations.IsDataBound(this, ItemsSourceProperty))
            {
                IList list = ItemsSource as IList;
                if (list != null)
                {
                    return(list.Count);
                }

                // ItemsSource is only an IEnumerable
                int         i          = 0;
                IEnumerator enumerator = ItemsSource.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    i++;
                }
                return(i);
            }

            if (Items != null)
            {
                return(Items.Count);
            }

            return(0);
        }
示例#20
0
        /// <summary>
        /// Gets all bindings.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        /// <remarks>http://stackoverflow.com/questions/5150983/how-to-invoke-updatesource-for-all-bindings-on-the-form</remarks>
        public static IEnumerable <BindingExpression> GetAllBindings(this DependencyObject obj)
        {
            var stack = new Stack <DependencyObject>();

            stack.Push(obj);

            while (stack.Count > 0)
            {
                var cur = stack.Pop();
                var lve = cur.GetLocalValueEnumerator();

                while (lve.MoveNext())
                {
                    if (BindingOperations.IsDataBound(cur, lve.Current.Property))
                    {
                        yield return(lve.Current.Value as BindingExpression);
                    }
                }

                int count = VisualTreeHelper.GetChildrenCount(cur);
                for (int i = 0; i < count; ++i)
                {
                    var child = VisualTreeHelper.GetChild(cur, i);
                    if (child is FrameworkElement)
                    {
                        stack.Push(child);
                    }
                }
            }
        }
示例#21
0
        /// <summary>
        /// Recorre todas las validaciones cargadas en el pariente para desactivarlas
        /// </summary>
        /// <param name="parent"></param>
        public static void LimpiarValidaciones(DependencyObject parent)
        {
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule reglaValidacion in binding.ValidationRules)
                    {
                        ValidationResult result = reglaValidacion.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expresion = BindingOperations.GetBindingExpression(parent, entry.Property);
                            System.Windows.Controls.Validation.ClearInvalid(expresion);
                        }
                    }
                }
            }
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                LimpiarValidaciones(child);
            }
        }
示例#22
0
 private static void ComputeAutoToolTip(TextBlock textBlock)
 {
     //
     // If the text block is not loaded, it doesn't make sense to check the ActualWidth.
     //
     if (!textBlock.IsLoaded)
     {
         return;
     }
     //
     // A ToolTip should be generated if it was not set locally by the user. Hence, if both:
     // 1. The ToolTip is not data bound in the xaml (by the user)
     // 2. The ToolTip is generated before OR [it is null (i.e. not set by the user)]
     //
     if (
         textBlock.Tag != null ||
         !(BindingOperations.IsDataBound(textBlock, FrameworkElement.ToolTipProperty) && textBlock.ToolTip != null)
         )
     {
         textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
         var width = textBlock.DesiredSize.Width - textBlock.Margin.Left - textBlock.Margin.Right;
         ToolTipService.SetToolTip(textBlock, textBlock.ActualWidth < width ? textBlock.Text : null);
         ToolTipService.SetShowOnDisabled(textBlock, true);
         //
         // Ok ok, let's use a tag to indicate the tooltip was generated (and thus, could be not-null).
         // Don't use some cached list with TextBlocks because this will lead to memory leaks.
         //
         textBlock.Tag = new object();
     }
 }
示例#23
0
        private static void EndEditing(DependencyObject dependencyObject)
        {
            Debug.Assert(dependencyObject != null);

            // When in custom control templates, the GetLocalValueEnumerator doesn't return bound values to the templated parent, so I iterate All properties.
            foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dependencyObject, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.All) }))
            {
                DependencyPropertyDescriptor dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(propertyDescriptor);
                if (dependencyPropertyDescriptor != null)
                {
                    DependencyProperty dependencyProperty = dependencyPropertyDescriptor.DependencyProperty;

                    if (BindingOperations.IsDataBound(dependencyObject, dependencyProperty))
                    {
                        BindingExpression binding = BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty);
                        if (binding != null)
                        {
                            binding.UpdateSource();
                        }
                    }
                }
            }

            int childrenCount = VisualTreeHelper.GetChildrenCount(dependencyObject);

            for (int i = 0; i < childrenCount; i++)
            {
                DependencyObject childDependencyObject = VisualTreeHelper.GetChild(dependencyObject, i);
                EndEditing(childDependencyObject);
            }
        }
示例#24
0
        /// <summary>
        /// Marks the specified FrameworkElement as invalid using the DummyRule
        /// in combination with the DummyErrorProperty to fabricate a ValidationError.
        /// </summary>
        /// <param name="frameworkElement">The framework element that is supposed to have a validation error.</param>
        /// <param name="errorContent">Content of the error that is added to the framework element.</param>
        /// <param name="newMark">if set to <c>true</c> a new error is simply added else
        /// any existing error is cleared before adding.</param>
        /// <exception cref="ArgumentNullException" />
        public static void MarkInvalid(FrameworkElement frameworkElement, object errorContent, bool newMark)
        {
            if (frameworkElement == null)
            {
                throw new ArgumentNullException("Argument 'frameworkElement' must not be null.");
            }

            if (newMark)
            {
                DummyRule.ClearInvalid(frameworkElement);
            }

            if (!BindingOperations.IsDataBound(frameworkElement, DummyRule.DummyErrorProperty))
            {
                DummyRule rule    = new DummyRule(false, errorContent);
                Binding   binding = new Binding("ErrorContent")
                {
                    Source = rule
                };
                binding.ValidationRules.Add(rule);
                BindingOperations.SetBinding(frameworkElement, DummyRule.DummyErrorProperty, binding);

                BindingExpression bindex = BindingOperations.GetBindingExpression(frameworkElement, DummyRule.DummyErrorProperty);

                Validation.MarkInvalid(bindex, new ValidationError(rule, binding, errorContent, null));

                bindex.UpdateSource();
            }
        }
        public void CreateStateEditorTest()
        {
            var element = StateEditor.CreateElement(new object(), BindingMode.Default);

            Assert.IsNotNull(element);

            Assert.IsTrue(BindingOperations.IsDataBound(element, Selector.SelectedValueProperty));
        }
示例#26
0
        /// <summary>
        /// Returns a value that indicates whether the specified property is currently data-bound.
        /// </summary>
        /// <param name="target">The object where <paramref name="property"/> is.</param>
        /// <param name="property">The dependency property to check.</param>
        /// <returns>True if the specified property is data-bound, otherwise False.</returns>
        public static bool IsDataBound(DependencyObject target, DependencyProperty property)
        {
#if NETFX_CORE
            return(target.ReadLocalValue(property) is BindingExpressionBase);
#else
            return(BindingOperations.IsDataBound(target, property));
#endif
        }
示例#27
0
        /// <summary>
        /// Binds default properties of control to quick access element
        /// </summary>
        /// <param name="source">Source item</param>
        /// <param name="element">Toolbar item</param>
        public static void BindQuickAccessItem(FrameworkElement source, FrameworkElement element)
        {
            Bind(source, element, nameof(source.DataContext), DataContextProperty, BindingMode.OneWay);

            if (source is ICommandSource)
            {
                if (source is MenuItem)
                {
                    Bind(source, element, nameof(ICommandSource.CommandParameter), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(ICommandSource.CommandTarget), System.Windows.Controls.MenuItem.CommandTargetProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(ICommandSource.Command), System.Windows.Controls.MenuItem.CommandProperty, BindingMode.OneWay);
                }
                else
                {
                    Bind(source, element, nameof(ICommandSource.CommandParameter), ButtonBase.CommandParameterProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(ICommandSource.CommandTarget), ButtonBase.CommandTargetProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(ICommandSource.Command), ButtonBase.CommandProperty, BindingMode.OneWay);
                }
            }

            Bind(source, element, nameof(FontFamily), FontFamilyProperty, BindingMode.OneWay);
            Bind(source, element, nameof(FontSize), FontSizeProperty, BindingMode.OneWay);
            Bind(source, element, nameof(FontStretch), FontStretchProperty, BindingMode.OneWay);
            Bind(source, element, nameof(FontStyle), FontStyleProperty, BindingMode.OneWay);
            Bind(source, element, nameof(FontWeight), FontWeightProperty, BindingMode.OneWay);

            Bind(source, element, nameof(Foreground), ForegroundProperty, BindingMode.OneWay);
            Bind(source, element, nameof(IsEnabled), IsEnabledProperty, BindingMode.OneWay);
            Bind(source, element, nameof(Opacity), OpacityProperty, BindingMode.OneWay);
            Bind(source, element, nameof(SnapsToDevicePixels), SnapsToDevicePixelsProperty, BindingMode.OneWay);

            Bind(source, element, new PropertyPath(FocusManager.IsFocusScopeProperty), FocusManager.IsFocusScopeProperty, BindingMode.OneWay);

            if (source is IHeaderedControl headeredControl)
            {
                if (headeredControl is HeaderedItemsControl)
                {
                    Bind(source, element, nameof(HeaderedItemsControl.Header), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(HeaderedItemsControl.HeaderStringFormat), HeaderedItemsControl.HeaderStringFormatProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(HeaderedItemsControl.HeaderTemplate), HeaderedItemsControl.HeaderTemplateProperty, BindingMode.OneWay);
                    Bind(source, element, nameof(HeaderedItemsControl.HeaderTemplateSelector), HeaderedItemsControl.HeaderTemplateSelectorProperty, BindingMode.OneWay);
                }
                else
                {
                    Bind(source, element, nameof(IHeaderedControl.Header), HeaderProperty, BindingMode.OneWay);
                }

                if (source.ToolTip is not null ||
                    BindingOperations.IsDataBound(source, ToolTipProperty))
                {
                    Bind(source, element, nameof(ToolTip), ToolTipProperty, BindingMode.OneWay);
                }
                else
                {
                    Bind(source, element, nameof(IHeaderedControl.Header), ToolTipProperty, BindingMode.OneWay);
                }
            }
        /// <summary>
        /// Checks all the validation rules associated with objects, forces the binding to execute all their validation rules.
        /// </summary>
        /// <param name="parent">The parent <see cref="DependencyObject"/>.</param>
        /// <returns>True if valid.</returns>
        public static bool IsValid(DependencyObject parent)
        {
            // parent properties validation
            var valid = true;

            // get the list of all the dependency properties, we can use a level of caching to avoid to use reflection
            // more than one time for each object
            foreach (var dp in GetDepenedencyProperties(parent.GetType()))
            {
                if (!BindingOperations.IsDataBound(parent, dp))
                {
                    continue;
                }

                var binding = BindingOperations.GetBinding(parent, dp);
                if ((binding == null) || (binding.ValidationRules.Count <= 0))
                {
                    continue;
                }

                var expression = BindingOperations.GetBindingExpression(parent, dp);
                if (expression == null)
                {
                    continue;
                }

                switch (binding.Mode)
                {
                case BindingMode.OneTime:
                case BindingMode.OneWay:
                    expression.UpdateTarget();
                    break;

                default:
                    expression.UpdateSource();
                    break;
                }

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

            // Children properties validation
            for (var i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (!IsValid(child))
                {
                    valid = false;
                }
            }

            return(valid);
        }
示例#29
0
 protected override void OnValueChanged(double oldValue, double newValue)
 {
     base.OnValueChanged(oldValue, newValue);
     if (!this.m_withinChanging && !BindingOperations.IsDataBound(this, HueProperty))
     {
         this.m_withinChanging = true;
         this.Hue = 360.0 - newValue;
         this.m_withinChanging = false;
     }
 }
        private async void btnSaveTxt2Bin_Click(object sender, RoutedEventArgs e)
        {
            // Выключим кнопку записи в файл чтобы сто раз не жмакали
            // так как у нас включен биндинг, нужно его засейвить  потом ресторить.
            var         btn     = ((Button)sender);
            BindingBase binding = null;

            if (BindingOperations.IsDataBound(btn, IsEnabledProperty))
            {
                binding = BindingOperations.GetBinding(btn, IsEnabledProperty) ??
                          (BindingBase)BindingOperations.GetMultiBinding(btn, IsEnabledProperty);
            }

            btn.IsEnabled = false;

            // Читаем ввод пользователя. Валидация ввода провдится еще в фазе ввода в форму.
            var binPrefix = tbxBinPrefix.Text;
            var filePath  = tbxTxtPath.Text;

            // Инициализируем прогресс бар
            prgbTxt2Bin.IsIndeterminate = true;

            // прогрессор, будет апдейтить прогрессбар и строку статуса
            var progress = new Progress <ProgressReport>(report =>
            {
                var str = "";
                if (report.Finished)
                {
                    str = "Обработано: {0}   Затрачено: {1}".Put(report.ProcessedCount, report.TimeUsed);
                }
                else
                {
                    str = "Обработано: {0}   Текущий: {1}   Затрачено: {2}".Put(report.ProcessedCount, report.Date.Date.ToShortDateString(), report.TimeUsed);
                }

                lblBarProcessStatus.Content = str;
            });

            // заводим асинхронно конвертацию, если будут ошибки, они хэндлятся штатным образом.
            try
            {
                await Common.TxtToBinTradesAsync(filePath, binPrefix, progress);
            }
            catch (Exception ex)
            {
                Trace.Fail(ex.ToString());
                lblBarProcessStatus.Content = "Error: {0}".Put(ex.Message);
                this.UpdateLayout();
            }

            // восстановим биндинг кнопки, сбросим прогрессбар
            btn.SetBinding(IsEnabledProperty, binding);
            prgbTxt2Bin.IsIndeterminate = false;
            prgbTxt2Bin.Value           = 0;
        }