Example #1
0
        private void UpdateListBinding()
        {
            BindingBase bindBase = BindingOperations.GetBindingBase(lstvItems, ListView.ItemsSourceProperty);

            BindingOperations.ClearBinding(lstvItems, ListView.ItemsSourceProperty);
            lstvItems.SetBinding(ListView.ItemsSourceProperty, bindBase);
        }
Example #2
0
        public static List <BindingBase> GetBindingObjects(this DependencyObject element)
        {
            Console.WriteLine("GetBindingObjects -> {0}", element);
            List <BindingBase>        bindings = new List <BindingBase>();
            List <DependencyProperty> dpList   = new List <DependencyProperty>();

            dpList.AddRange(GetDependencyProperties(element));
            //dpList.AddRange(GetAttachedProperties(element));
            foreach (DependencyProperty dp in dpList)
            {
                Console.WriteLine("{1}.{0}", dp.Name, element);
                BindingBase b = BindingOperations.GetBindingBase(element as DependencyObject, dp);
                if (b != null)
                {
                    bindings.Add(b);
                }
            }
            int childrenCount = VisualTreeHelper.GetChildrenCount(element);

            Console.WriteLine("{1}.ChildrenCount: {0}", childrenCount, element);
            if (childrenCount > 0)
            {
                for (int i = 0; i < childrenCount; i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(element, i);
                    bindings.AddRange(GetBindingObjects(child));
                }
            }
            return(bindings);
        }
        /// <summary>
        /// Frameworks the element on data context changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private void FrameworkElementOnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            OnDataContextDetaching(e.OldValue);
            var properties = GetDependencyProperties(this);

            foreach (var dependencyProperty in properties)
            {
                var bindingBase = BindingOperations.GetBindingBase(this, dependencyProperty);
                switch (bindingBase)
                {
                case Binding binding:
                {
                    if (binding.Source != null ||
                        binding.RelativeSource != null ||
                        binding.ElementName != null)
                    {
                        continue;
                    }
                    BindingOperations.ClearBinding(this, dependencyProperty);
                    BindingOperations.SetBinding(this, dependencyProperty, binding);
                    break;
                }
                }
            }
            OnDataContextAttached(e.NewValue);
        }
        /// <summary>
        /// Tries to resolve path binding and to set whole binding accordingly.
        /// </summary>
        /// <param name="serviceProvider">Service provider given by the framework.</param>
        private void Initialize(IServiceProvider serviceProvider = null)
        {
            if (initialized)
            {
                return;
            }

            if (ResolveBoundPathBinding(serviceProvider))
            {
                if (!providing_value)  // set binding only if we are not called by the ProvideValue method.
                {
                    no_target_update = true;
                    BindingOperations.SetBinding(TargetObject, TargetProperty, boundPathBinding);
                    no_target_update = false;
                }

                initialized = true;
            }
            else if (!providing_value && TargetObject != null)  // if unresolved and target object is identified, try to clear property binding.
            {
                if (BindingOperations.GetBindingBase(TargetObject, TargetProperty) != null)
                {
                    no_target_update = true;
                    BindingOperations.ClearBinding(TargetObject, TargetProperty); // may fail in datatemplates, but self binding is at least maintained.
                    no_target_update = false;
                }
            }
        }
Example #5
0
        /// <summary>
        /// Эту процедуру нужно привязать к событию GotFocus для всех TextBox, в которых используются Binding и StrToIntConverter, StrToFloatConverter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void txt_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBoxEx txt = sender as TextBoxEx;

            if (txt != null && txt.Modified && txt.IsRightInput)
            {
                BindingBase bindBase = BindingOperations.GetBindingBase(txt, TextBox.TextProperty);

                if (bindBase != null)
                {
                    Binding bind = bindBase as Binding;
                    if (bind != null)
                    {
                        if (bind.Converter is StrToIntConverter)
                        {
                            ((StrToIntConverter)bind.Converter).m_PrevVal = int.Parse(txt.Text);
                        }
                        else
                        if (bind.Converter is StrToFloatConverter)
                        {
                            ((StrToFloatConverter)bind.Converter).m_PrevVal = float.Parse(txt.Text);
                        }
                    }
                }
            }
        }
Example #6
0
            public override void Desynchronize()
            {
                var targetColumn  = this.DetailColumn;
                var dp            = ColumnBase.VisibleProperty;
                var oldLocalValue = m_localValue;

                m_localValue = DependencyProperty.UnsetValue;

                if (BindingOperations.GetBindingBase(targetColumn, dp) != null)
                {
                    return;
                }

                if (!object.Equals(targetColumn.ReadLocalValue(dp), false))
                {
                    return;
                }

                var oldBinding = oldLocalValue as BindingBase;

                if (oldBinding != null)
                {
                    BindingOperations.SetBinding(targetColumn, dp, oldBinding);
                }
                else if (oldLocalValue != DependencyProperty.UnsetValue)
                {
                    targetColumn.SetValue(dp, oldLocalValue);
                }
                else
                {
                    targetColumn.ClearValue(dp);
                }
            }
Example #7
0
        public override void SetProperties(UserControl[] _controls)
        {
            var tb = BindingOperations.GetBindingBase(this, TextProperty);

            BindingOperations.ClearBinding(this, TextProperty);

            if (Items == null)
            {
                Items = new ObservableCollection <string>();
            }
            Items.Clear();
            foreach (var item in (_controls.OfType <ListControl>().First()).Items)
            {
                Items.Add(item.Value);
            }
            UpdateBinding();

            DataSource   = new Triple <string, string, bool>();
            DataSource.A = _controls.OfType <DataSourceControl>().First().DataSource;
            DataSource.B = _controls.OfType <DataSourceControl>().First().DataProperty;
            DataSource.C = _controls.OfType <DataSourceControl>().First().Active;
            UpdateBinding();

            if (tb != null)
            {
                BindingOperations.SetBinding(this, TextProperty, tb);
            }

            base.SetProperties(_controls);
        }
            /// <summary>
            ///     Property changed callback for DataContext property
            /// </summary>
            private static void OnDataContextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                // Selector has a bug regarding DataContext change and SelectedItem property,
                // where if the SelectedItem due to old DataContext is a valid item in ItemsSource
                // but the SelectedItem due to new DataContext is not a valid item in ItemsSource,
                // the SelectedIndex remains that of old context instead of changing to -1.
                // This method is a workaround to that problem, since it is of high impact to DataGrid.
                TextBlockComboBox combo = (TextBlockComboBox)d;
                bool isLocalValue       = (DependencyPropertyHelper.GetValueSource(combo, SelectedItemProperty).BaseValueSource == BaseValueSource.Local);

                if (isLocalValue)
                {
                    // Clear the selection and re-apply the binding.
                    BindingBase binding = BindingOperations.GetBindingBase(combo, SelectedItemProperty);
                    if (binding != null)
                    {
                        combo.ClearValue(SelectedItemProperty);
                        DataGridPactComboBoxColumn.ApplyBinding(binding, combo, SelectedItemProperty);
                    }
                }
                else
                {
                    // Clear the selection by setting the local value
                    // and re-evaluate the property by clearing the local value.
                    combo.SelectedItem = null;
                    combo.ClearValue(SelectedItemProperty);
                }
            }
 /// <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;
         }
     }
 }
        /// <summary>
        /// Prepares this class to filter data based on resolved (or unresolved source).
        /// </summary>
        /// <param name="source">A source object to assess.</param>
        private void Initialize(object source)
        {
            if (initialized)
            {
                return;
            }

            // If source is resolved then set binding up:
            if (source != null)
            {
                ToggleBinding(source);
                initialized = true;

                // Check if source is a datacontext, in which case subscribe to datacontext changed event:
                if (IsInnerSourceDatacontext && TargetObject != null)
                {
                    (TargetObject as FrameworkElement).DataContextChanged += DatacontextTarget_DataContextChanged;
                }
            }
            // else clear current binding since we cannot know if source type is correct:
            else if (TargetObject != null)  // but only if target object is identified.
            {
                // Try to clear current binding while source isn't resolved, since it could be of another
                // type as the accepted one and to free the identity binding processing:
                if (BindingOperations.GetBindingBase(TargetObject, TargetProperty) != null)
                {
                    BindingOperations.ClearBinding(TargetObject, TargetProperty);
                }
            }
        }
Example #11
0
            public override void Synchronize()
            {
                var targetColumn = this.DetailColumn;
                var dp           = ColumnBase.VisibleProperty;

                var currentBinding = BindingOperations.GetBindingBase(targetColumn, dp);

                if (currentBinding != null)
                {
                    m_localValue = currentBinding;
                    BindingOperations.ClearBinding(targetColumn, dp);
                }
                else
                {
                    var localValue = targetColumn.ReadLocalValue(dp);

                    // The appropriate value is still in place.
                    if (object.Equals(localValue, false))
                    {
                        return;
                    }

                    m_localValue = localValue;
                }

                // Hide the column.
                targetColumn.SetValue(dp, false);
            }
            private static void StoreLocalValue(Dictionary <DependencyProperty, object> store, ColumnBase column, DependencyProperty property)
            {
                Debug.Assert(store != null);
                Debug.Assert(column != null);
                Debug.Assert(property != null);

                var binding = BindingOperations.GetBindingBase(column, property);

                if (binding != null)
                {
                    store[property] = binding;
                }
                else
                {
                    var value = column.ReadLocalValue(property);
                    if (value != DependencyProperty.UnsetValue)
                    {
                        store[property] = value;
                    }
                    else
                    {
                        store.Remove(property);
                    }
                }
            }
        /// <summary>
        /// Determines whether a particular dependency property already has a binding on the provided element.
        /// </summary>
        public static bool HasBinding(FrameworkElement element, DependencyProperty property)
        {
#if NET
            return(BindingOperations.GetBindingBase(element, property) != null);
#else
            return(element.GetBindingExpression(property) != null);
#endif
        }
Example #14
0
        public static void TransferPropertyTo(this DependencyObject original,
                                              DependencyObject clone,
                                              DependencyProperty originalProperty,
                                              DependencyProperty cloneProperty = null,
                                              bool templateBoundOnly           = false)
        {
            if (original == null)
            {
                throw new ArgumentNullException(nameof(original));
            }
            if (clone == null)
            {
                throw new ArgumentNullException(nameof(clone));
            }
            if (originalProperty == null)
            {
                throw new ArgumentNullException(nameof(originalProperty));
            }

            cloneProperty = cloneProperty ?? originalProperty;

            var originalValueSource = DependencyPropertyHelper.GetValueSource(original, originalProperty).BaseValueSource;
            var performTransfer     = templateBoundOnly ? originalValueSource >= BaseValueSource.ParentTemplate : originalValueSource > BaseValueSource.Default;

            if (!performTransfer)
            {
                return;
            }

            var binding = BindingOperations.GetBindingBase(original, originalProperty);

            if (binding != null)
            {
                // Transfer Bindings
                BindingOperations.SetBinding(clone, cloneProperty, binding);
            }
            else
            {
                if (original.ReadLocalValue(originalProperty) is Expression expression)
                {
                    // Transfer DynamicResource
                    if (ResourceReferenceExpressionConverter.ConvertTo(expression, typeof(MarkupExtension)) is DynamicResourceExtension dynamicResource)
                    {
                        clone.SetValue(cloneProperty, dynamicResource.ProvideValue(null));
                    }
                }
                else
                {
                    // Transfer other DPs
                    var originalValue = original.GetValue(originalProperty);
                    clone.SetValue(cloneProperty, originalValue);
                }
            }
        }
Example #15
0
        protected override void OnDropDownOpened(EventArgs e)
        {
            base.OnDropDownOpened(e);
            BindingBase bindingBase = BindingOperations.GetBindingBase((DependencyObject)this, OnDemandComboBox.ItemsListProperty);

            if (bindingBase == null)
            {
                return;
            }
            BindingOperations.SetBinding((DependencyObject)this, ItemsControl.ItemsSourceProperty, bindingBase);
        }
Example #16
0
        static void RelativeVisibilityPropertyChangedCallback(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            var obj = target as UIElement;

            obj.Visibility = (Visibility)e.NewValue;
            var binding = (IRelativeBinding)BindingOperations.GetBindingBase(obj, RelativeVisibilityProperty);

            if (binding != null)
            {
                UpdateSpecifiedAncestorTypeVisibility(obj, binding.AncestorType, binding.AncestorLevel);
            }
        }
Example #17
0
        public override void SetProperties(UserControl[] _controls)
        {
            var tb = BindingOperations.GetBindingBase(this, TextProperty);

            BindingOperations.ClearBinding(this, TextProperty);

            if (Items == null)
            {
                Items = new ObservableCollection <string>();
            }

            //Update Items instead of clearing
            var newItems = (_controls.OfType <ListControl>().First()).Items;

            for (int i = 0; i < Math.Max(Items.Count, newItems.Count); i++)
            {
                if (i < Math.Min(Items.Count, newItems.Count))
                {
                    if (Items[i] != newItems[i].Value)
                    {
                        Items[i] = newItems[i].Value;
                    }
                }
                else if (Items.Count < newItems.Count)
                {
                    Items.Add(newItems[i].Value);
                }
            }
            while (Items.Count > newItems.Count)
            {
                Items.RemoveAt(Items.Count - 1);
            }

            //UpdateBinding();

            DataSource = new Triple <string, string, bool>
            {
                A = _controls.OfType <DataSourceControl>().First().DataSource,
                B = _controls.OfType <DataSourceControl>().First().DataProperty,
                C = _controls.OfType <DataSourceControl>().First().Active
            };
            UpdateBinding();

            if (tb != null)
            {
                BindingOperations.SetBinding(this, TextProperty, tb);
            }

            base.SetProperties(_controls);
        }
Example #18
0
        private static IEnumerable <Tuple <BindingBase, DependencyProperty> > GetLocalBindings(DependencyObject root)
        {
            var localValueEnumerator = root.GetLocalValueEnumerator();

            while (localValueEnumerator.MoveNext())
            {
                var dp      = localValueEnumerator.Current.Property;
                var binding = BindingOperations.GetBindingBase(root, dp);
                if (binding != null)
                {
                    yield return(Tuple.Create(binding, dp));
                }
            }
        }
Example #19
0
            private bool m_isListeningEvents; //false

            #endregion

            public override void Synchronize()
            {
                this.SubscribeEvents();

                var targetColumn = this.DetailColumn;

                foreach (var entry in m_bindings)
                {
                    var dp      = entry.Key;
                    var binding = entry.Value;

                    // The appropriate binding is still in place.
                    var currentBinding = BindingOperations.GetBindingBase(targetColumn, dp);
                    if (currentBinding == binding)
                    {
                        continue;
                    }

                    if (currentBinding != null)
                    {
                        m_localValues[dp] = currentBinding;
                    }
                    else
                    {
                        var localValue = targetColumn.ReadLocalValue(dp);
                        if (localValue != DependencyProperty.UnsetValue)
                        {
                            m_localValues[dp] = localValue;
                        }
                        else
                        {
                            m_localValues.Remove(dp);
                        }
                    }

                    BindingOperations.SetBinding(targetColumn, dp, binding);
                }

                var visiblePosition = this.GetTargetVisiblePosition();

                if (visiblePosition.HasValue)
                {
                    targetColumn.VisiblePosition = visiblePosition.Value;
                }
                else
                {
                    targetColumn.ClearValue(ColumnBase.VisiblePositionProperty);
                }
            }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="dependencyObject"></param>
        /// <param name="sources"></param>
        /// <remarks>
        /// Based on ASanch answer on http://stackoverflow.com/questions/3959421/wpf-find-control-that-binds-to-specific-property
        /// </remarks>>
        private static void GetDependencyObjectsWithBindingToPropertyRecursive(string propertyName, DependencyObject dependencyObject, ICollection <DependencyObject> sources)
        {
            var dependencyProperties = new List <DependencyProperty>();

            dependencyProperties.AddRange(MarkupWriter.GetMarkupObjectFor(dependencyObject).Properties.Where(x => x.DependencyProperty != null).Select(x => x.DependencyProperty).ToList());
            dependencyProperties.AddRange(
                MarkupWriter.GetMarkupObjectFor(dependencyObject).Properties.Where(x => x.IsAttached && x.DependencyProperty != null).Select(x => x.DependencyProperty).ToList());

            var bindings = dependencyProperties.Select(x => BindingOperations.GetBindingBase(dependencyObject, x)).Where(x => x != null).ToList();

            Predicate <Binding> condition = binding => binding != null && binding.Path.Path == propertyName && !sources.Contains(dependencyObject);

            foreach (var bindingBase in bindings)
            {
                if (bindingBase is Binding)
                {
                    if (condition(bindingBase as Binding))
                    {
                        sources.Add(dependencyObject);
                    }
                }
                else if (bindingBase is MultiBinding)
                {
                    if (((MultiBinding)bindingBase).Bindings.Any(bindingBase2 => condition(bindingBase2 as Binding)))
                    {
                        sources.Add(dependencyObject);
                    }
                }
                else if (bindingBase is PriorityBinding)
                {
                    if (((PriorityBinding)bindingBase).Bindings.Any(bindingBase2 => condition(bindingBase2 as Binding)))
                    {
                        sources.Add(dependencyObject);
                    }
                }
            }

            var children = LogicalTreeHelper.GetChildren(dependencyObject).OfType <DependencyObject>().ToList();

            if (children.Count == 0)
            {
                return;
            }

            foreach (var child in children)
            {
                GetDependencyObjectsWithBindingToPropertyRecursive(propertyName, child, sources);
            }
        }
Example #21
0
 protected override void SetBindings(FrameworkElement primaryBindingTarget)
 {
     if (ItemsSource != null)
     {
         BindingBase itemsSourceBinding = BindingOperations.GetBindingBase(this, ItemsSourceProperty);
         if (itemsSourceBinding != null)
         {
             BindingOperations.SetBinding(primaryBindingTarget, ItemsControl.ItemsSourceProperty, itemsSourceBinding);
         }
         else
         {
             primaryBindingTarget.SetValue(ItemsControl.ItemsSourceProperty, ItemsSource);
         }
     }
 }
Example #22
0
        public static BindingBase GetBindingOf(
            this DependencyObject dependencyObject,
            DependencyProperty dependencyProperty
            )
        {
            if (dependencyObject == null)
            {
                return(null);
            }

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

            return(BindingOperations.GetBindingBase(dependencyObject, dependencyProperty));
        }
Example #23
0
        /// <summary>
        /// Updates the binding base.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="dependencyProperty">The dependency property.</param>
        public static void UpdateBindingBase([NotNull] this DependencyObject target, [NotNull] DependencyProperty dependencyProperty)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (dependencyProperty == null)
            {
                throw new ArgumentNullException(nameof(dependencyProperty));
            }
            var bindingBase = BindingOperations.GetBindingBase(target, dependencyProperty);

            if (bindingBase == null)
            {
                return;
            }
            UpdateBindingBase(target, dependencyProperty, bindingBase);
        }
Example #24
0
        /// <summary>
        /// Returns all direct bindings for a given object
        /// </summary>
        /// <param name="element">The object to check</param>
        /// <returns>List of bindings</returns>
        public static List <BindingBase> GetBindingObjects(Object element)
        {
            List <BindingBase>        bindings = new List <BindingBase>();
            List <DependencyProperty> dpList   = new List <DependencyProperty>();

            dpList.AddRange(GetDependencyProperties(element));
            dpList.AddRange(GetAttachedProperties(element));

            foreach (DependencyProperty dp in dpList)
            {
                BindingBase b = BindingOperations.GetBindingBase(element as DependencyObject, dp);
                if (b != null)
                {
                    bindings.Add(b);
                }
            }

            return(bindings);
        }
Example #25
0
        private object GetPropertyValue(DependencyProperty property)
        {
            object result = null;

            if (BindingOperations.IsDataBound(this, property))
            {
                result = BindingOperations.GetBindingBase(this, property);
                if (result == null)
                {
                    result = BindingOperations.GetBindingExpressionBase(this, property);
                }
            }
            else
            {
                result = GetValue(property);
            }

            return(result);
        }
        private static void OnDummyImagePropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
        {
            Image animatedImage = (Image)dpo;

            if (!animatedImage.GetIsAnimationChangingFrame())
            {
                BindingBase originalBinding = BindingOperations.GetBindingBase(dpo, DummyImageProperty);
                if (originalBinding != null)
                {
                    BindingOperations.SetBinding(dpo, Image.SourceProperty, originalBinding);
                    BindingOperations.ClearBinding(animatedImage, DummyImageProperty);
                }
                animatedImage.SetIsAnimationChangingFrame(false);
            }
            else
            {
                animatedImage.SetIsAnimationChangingFrame(false);
            }

            animatedImage.SetIsAnimationChangingFrame(false);
        }
Example #27
0
        /// <summary>
        /// Creates Window-specific bindings (e.g. Title) between Window and its ViewModel
        /// </summary>
        /// <param name="viewModel">ViewModel to bind to</param>
        /// <param name="window">Window to attach handlers for</param>
        /// <param name="isDialog">True if Window is modal dialog, false if it's independent Window</param>
        protected virtual void BindWindow(object viewModel, Window window, bool isDialog)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }

            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            if (viewModel is IHaveTitle && string.IsNullOrEmpty(window.Title) &&
                BindingOperations.GetBindingBase(window, Window.TitleProperty) == null)
            {
                window.SetBinding(Window.TitleProperty, new Binding(nameof(IHaveTitle.Title))
                {
                    Mode = BindingMode.OneWay,
                });
            }
        }
Example #28
0
            public override void Desynchronize()
            {
                this.UnsubscribeEvents();

                var targetColumn = this.DetailColumn;

                foreach (var entry in m_bindings)
                {
                    var dp      = entry.Key;
                    var binding = entry.Value;

                    // The appropriate binding is still in place.
                    var currentBinding = BindingOperations.GetBindingBase(targetColumn, dp);
                    if (currentBinding == binding)
                    {
                        object oldValue;

                        if (m_localValues.TryGetValue(dp, out oldValue))
                        {
                            var oldBinding = oldValue as BindingBase;
                            if (oldBinding != null)
                            {
                                BindingOperations.SetBinding(targetColumn, dp, oldBinding);
                            }
                            else
                            {
                                targetColumn.SetValue(dp, oldValue);
                            }
                        }
                        else
                        {
                            BindingOperations.ClearBinding(targetColumn, dp);
                        }
                    }

                    m_localValues.Remove(dp);
                }

                targetColumn.ClearValue(ColumnBase.VisiblePositionProperty);
            }
        /// <summary>
        /// Update the current image source to the relevant frame.
        /// </summary>
        /// <param name="dpo"></param>
        /// <param name="e"></param>
        private static void OnCurrentFrameIndexChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
        {
            Image animatedImage = (Image)dpo;

            if (!animatedImage.GetIsAnimationChangingFrame())
            {
                animatedImage.SetIsAnimationChangingFrame(true);

                bool hasBinding = BindingOperations.IsDataBound(animatedImage, Image.SourceProperty);
                if (hasBinding)
                {
                    BindingBase originalBinding = BindingOperations.GetBindingBase(animatedImage, Image.SourceProperty);
                    BindingOperations.SetBinding(animatedImage, DummyImageProperty, originalBinding);
                }
                animatedImage.Source = ((BitmapFrame)animatedImage.Source).Decoder.Frames[(int)e.NewValue];

                if (!hasBinding)
                {
                    animatedImage.SetIsAnimationChangingFrame(false);
                }
            }
        }
Example #30
0
        /// <summary>
        /// Given a ViewModel, create its View, ensure that it's a Window, and set it up
        /// </summary>
        /// <param name="viewModel">ViewModel to create the window for</param>
        /// <param name="isDialog">True if the window will be used as a dialog</param>
        /// <param name="ownerViewModel">Optionally the ViewModel which owns the view which should own this window</param>
        /// <returns>Window which was created and set up</returns>
        protected virtual Window CreateWindow(object viewModel, bool isDialog, IViewAware ownerViewModel)
        {
            var view   = this.viewManager.CreateAndBindViewForModelIfNecessary(viewModel);
            var window = view as Window;

            if (window == null)
            {
                var e = new StyletInvalidViewTypeException(String.Format("WindowManager.ShowWindow or .ShowDialog tried to show a View of type '{0}', but that View doesn't derive from the Window class. " +
                                                                         "Make sure any Views you display using WindowManager.ShowWindow or .ShowDialog derive from Window (not UserControl, etc)",
                                                                         view == null ? "(null)" : view.GetType().Name));
                logger.Error(e);
                throw e;
            }

            // Only set this it hasn't been set / bound to anything
            var haveDisplayName = viewModel as IHaveDisplayName;

            if (haveDisplayName != null && (String.IsNullOrEmpty(window.Title) || window.Title == view.GetType().Name) && BindingOperations.GetBindingBase(window, Window.TitleProperty) == null)
            {
                var binding = new Binding("DisplayName")
                {
                    Mode = BindingMode.TwoWay
                };
                window.SetBinding(Window.TitleProperty, binding);
            }

            if (ownerViewModel?.View is Window explicitOwner)
            {
                window.Owner = explicitOwner;
            }
            else if (isDialog)
            {
                var owner = this.InferOwnerOf(window);
                if (owner != null)
                {
                    // We can end up in a really weird situation if they try and display more than one dialog as the application's closing
                    // Basically the MainWindow's no long active, so the second dialog chooses the first dialog as its owner... But the first dialog
                    // hasn't yet been shown, so we get an exception ("cannot set owner property to a Window which has not been previously shown").
                    try
                    {
                        window.Owner = owner;
                    }
                    catch (InvalidOperationException e)
                    {
                        logger.Error(e, "This can occur when the application is closing down");
                    }
                }
            }

            if (isDialog)
            {
                logger.Info("Displaying ViewModel {0} with View {1} as a Dialog", viewModel, window);
            }
            else
            {
                logger.Info("Displaying ViewModel {0} with View {1} as a Window", viewModel, window);
            }

            // If and only if they haven't tried to position the window themselves...
            // Has to be done after we're attempted to set the owner
            if (window.WindowStartupLocation == WindowStartupLocation.Manual && Double.IsNaN(window.Top) && Double.IsNaN(window.Left) &&
                BindingOperations.GetBinding(window, Window.TopProperty) == null && BindingOperations.GetBinding(window, Window.LeftProperty) == null)
            {
                window.WindowStartupLocation = window.Owner == null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner;
            }

            // This gets itself retained by the window, by registering events
            // ReSharper disable once ObjectCreationAsStatement
            new WindowConductor(window, viewModel);

            return(window);
        }