C# (CSharp) Класс System.Windows. DependencyObject Code Examples

C# (CSharp) System.Windows.DependencyObject - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для класса System.Windows.DependencyObject, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Наследование: INativeDependencyObjectWrapper, IRefContainer
Пример #1
0
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            TimelineDataItem data = item as TimelineDataItem;
            Product productItem;

            if (data == null)
            {
                productItem = item as Product;
            }
            else
            {
                productItem = data.DataItem as Product;
            }

            if (productItem == null)
            {
                return base.SelectTemplate(item, container);
            }

            if (productItem.Duration.Days != 0)
            {
                return this.ItemWithDurationTemplate;
            }
            else
            {
                return this.InstantItemTemplate;
            }
        }
        private static void OnScrollGroupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var scrollViewer = d as ScrollViewer;
            if (scrollViewer != null) {
                if (!string.IsNullOrEmpty((string)e.OldValue)) {
                    // Remove scrollviewer
                    if (scrollViewers.ContainsKey(scrollViewer)) {
                        scrollViewer.ScrollChanged -=
                          new ScrollChangedEventHandler(ScrollViewer_ScrollChanged);
                        scrollViewers.Remove(scrollViewer);
                    }
                }

                if (!string.IsNullOrEmpty((string)e.NewValue)) {
                    if (verticalScrollOffsets.Keys.Contains((string)e.NewValue)) {
                        scrollViewer.ScrollToVerticalOffset(verticalScrollOffsets[(string)e.NewValue]);
                    } else {
                        verticalScrollOffsets.Add((string)e.NewValue, scrollViewer.VerticalOffset);
                    }

                    // Add scrollviewer
                    scrollViewers.Add(scrollViewer, (string)e.NewValue);
                    scrollViewer.ScrollChanged += new ScrollChangedEventHandler(ScrollViewer_ScrollChanged);
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Gets the value of the <strong>AttachedDataContext</strong> attached property from a given 
        /// <see cref="DependencyObject"/> object.
        /// </summary>
        /// <param name="obj">The object from which to read the property value.</param>
        /// <return>The value of the <strong>AttachedDataContext</strong> attached property.</return>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="obj"/> is <see langword="null"/>.
        /// </exception>
        public static object GetAttachedDataContext(DependencyObject obj)
        {
            if (obj == null)
            throw new ArgumentNullException("obj");

              return obj.GetValue(AttachedDataContextProperty);
        }
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InteractionNode"/> class.
        /// </summary>
        /// <param name="uiElement">The UI element.</param>
        /// <param name="controller">The routed message controller.</param>
        public InteractionNode(DependencyObject uiElement, IRoutedMessageController controller)
        {
            _controller = controller;
            _uiElement = uiElement;

#if !SILVERLIGHT
            var element = _uiElement as FrameworkElement;
            if (element != null)
            {
                if (element.IsLoaded)
                    Element_Loaded(element, new RoutedEventArgs());
                else element.Loaded += Element_Loaded;
            }
            else
            {
                var fce = _uiElement as FrameworkContentElement;
                if (fce != null)
                {
                    if (fce.IsLoaded)
                        Element_Loaded(fce, new RoutedEventArgs());
                    else fce.Loaded += Element_Loaded;
                }
            }
#else
            var element = _uiElement as FrameworkElement;
            if(element != null) element.Loaded += Element_Loaded;
#endif
        }
Пример #5
0
 public static bool IsValid(DependencyObject node)
 {
     bool result;
     if (node != null)
     {
         if (Validation.GetHasError(node))
         {
             if (node is IInputElement)
             {
                 Keyboard.Focus((IInputElement)node);
             }
             result = false;
             return result;
         }
     }
     foreach (object subnode in LogicalTreeHelper.GetChildren(node))
     {
         if (subnode is DependencyObject)
         {
             if (!ValidationUtil.IsValid((DependencyObject)subnode))
             {
                 result = false;
                 return result;
             }
         }
     }
     result = true;
     return result;
 }
        /// <summary>
        ///     Called when HeaderProperty is invalidated on "d."
        /// </summary>
        private static void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            HeaderedContentControl ctrl = (HeaderedContentControl) d;

            ctrl.SetValue(HasHeaderPropertyKey, (e.NewValue != null) ? BooleanBoxes.TrueBox : BooleanBoxes.FalseBox);
            ctrl.OnHeaderChanged(e.OldValue, e.NewValue);
        }
Пример #7
0
 private static object CoerceText(DependencyObject d, object value)
 {
     MaskedTextBox textBox = (MaskedTextBox)d;
     MaskedTextProvider maskProvider = new MaskedTextProvider(textBox.Mask);
     maskProvider.Set((string)value);
     return maskProvider.ToDisplayString();            
 }
Пример #8
0
        private static void HandleIsEnabledChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            var textBlock = source as TextBlock;
            if (textBlock == null)
            {
                return;
            }

            if ((bool)e.OldValue)
            {
                var fader = GetFader(textBlock);
                if (fader != null)
                {
                    fader.Detach();
                    SetFader(textBlock, null);
                }

                textBlock.Loaded -= HandleTextBlockLoaded;
                textBlock.Unloaded -= HandleTextBlockUnloaded;
            }

            if ((bool)e.NewValue)
            {
                textBlock.Loaded += HandleTextBlockLoaded;
                textBlock.Unloaded += HandleTextBlockUnloaded;

                var fader = new Fader(textBlock);
                SetFader(textBlock, fader);
                fader.Attach();
            }
        }
Пример #9
0
 internal static void SetBinding(this DependencyObject sourceObject, DependencyObject targetObject, DependencyProperty sourceProperty, DependencyProperty targetProperty)
 {
     Binding b = new Binding();
     b.Source = sourceObject;
     b.Path = new PropertyPath(sourceProperty);
     BindingOperations.SetBinding(targetObject, targetProperty, b);
 }
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var ctxt = (container as FrameworkElement);
            if (ctxt == null) return null;

            if (item == null)
            {
                //System.Diagnostics.Trace.WriteLine("Warning: Null item in data template selector");
                return ctxt.FindResource("Empty") as DataTemplate;
            }

            // Allow type-specific data templates to take precedence (should we)?
            var key = new DataTemplateKey(item.GetType());
            var typeTemplate = ctxt.TryFindResource(key) as DataTemplate;
            if (typeTemplate != null)
                return typeTemplate;

            // Common problem if the MEF import failed to find any suitable DLLs
            if (!Renderers.Any())
                System.Diagnostics.Trace.WriteLine("Warning: No visualizer components loaded");

            var template = "";
            var r = Renderers
                .OrderByDescending(i => i.Importance)
                .FirstOrDefault(i => (i.CanRender(item, ref template)));
            if (r == null || String.IsNullOrEmpty(template))
            {
                System.Diagnostics.Trace.WriteLine("Warning: No renderers that can handle object");
                return ctxt.FindResource("Default") as DataTemplate;
            }

            return ctxt.TryFindResource(template) as DataTemplate ?? ctxt.FindResource("Missing") as DataTemplate;
        }
Пример #11
0
 private static void BusyCountChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     if (0.Equals(e.NewValue))
         SetIsBusy(d, false);
     else
         SetIsBusy(d, true);
 }
Пример #12
0
        private static void OnUserQueryChanged(DependencyObject s, UserQueryEntity uc)
        {
            UserQueryPermission.ViewUserQuery.Authorize();

            var currentEntity = UserAssetsClient.GetCurrentEntity(s);

            var csc = s as CountSearchControl;
            if (csc != null)
            {
                csc.QueryName = QueryClient.GetQueryName(uc.Query.Key);
                using (currentEntity == null ? null : CurrentEntityConverter.SetCurrentEntity(currentEntity))
                    UserQueryClient.ToCountSearchControl(uc, csc);
                csc.Search();
                return;
            }

            var sc = s as SearchControl;
            if (sc != null && sc.ShowHeader == false)
            {
                sc.QueryName = QueryClient.GetQueryName(uc.Query.Key);
                using (currentEntity == null ? null : CurrentEntityConverter.SetCurrentEntity(currentEntity))
                UserQueryClient.ToSearchControl(uc, sc);
                sc.Search();
                return;
            }

            return;
        }
Пример #13
0
    private static void OnIsPivotAnimatedChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
      ItemsControl list = d as ItemsControl;

      list.Loaded += (s2, e2) =>
        {
          // locate the pivot control that this list is within
          Pivot pivot = list.Ancestors<Pivot>().Single() as Pivot;

          // and its index within the pivot
          int pivotIndex = pivot.Items.IndexOf(list.Ancestors<PivotItem>().Single());

          bool selectionChanged = false;

          pivot.SelectionChanged += (s3, e3) =>
            {
              selectionChanged = true;
            };

          // handle manipulation events which occur when the user
          // moves between pivot items
          pivot.ManipulationCompleted += (s, e) =>
            {
              if (!selectionChanged)
                return;

              selectionChanged = false;

              if (pivotIndex != pivot.SelectedIndex)
                return;
              
              // determine which direction this tab will be scrolling in from
              bool fromRight = e.TotalManipulation.Translation.X <= 0;

              // locate the stack panel that hosts the items
              VirtualizingStackPanel vsp = list.Descendants<VirtualizingStackPanel>().First() as VirtualizingStackPanel;

              // iterate over each of the items in view
              int firstVisibleItem = (int)vsp.VerticalOffset;
              int visibleItemCount = (int)vsp.ViewportHeight;
              for (int index = firstVisibleItem; index <= firstVisibleItem + visibleItemCount; index++)
              {
                // find all the item that have the AnimationLevel attached property set
                var lbi = list.ItemContainerGenerator.ContainerFromIndex(index);
                if (lbi == null)
                  continue;

                vsp.Dispatcher.BeginInvoke(() =>
                  {
                    var animationTargets = lbi.Descendants().Where(p => ListAnimation.GetAnimationLevel(p) > -1);
                    foreach (FrameworkElement target in animationTargets)
                    {
                      // trigger the required animation
                      GetAnimation(target, fromRight).Begin();
                    }
                  });
              };
            };
        };
    }
Пример #14
0
 private static void OnDeckChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     var viewer = d as DeckCardsViewer;
     var newdeck = e.NewValue as MetaDeck ?? new MetaDeck(){IsCorrupt = true};
     var g = GameManager.Get().GetById(newdeck.GameId);
     viewer.deck = newdeck.IsCorrupt ?
         null
         : g == null ?
             null
             : newdeck;
     viewer._view = viewer.deck == null ? 
         new ListCollectionView(new List<MetaMultiCard>()) 
         : new ListCollectionView(viewer.deck.Sections.SelectMany(x => x.Cards).ToList());
     viewer.OnPropertyChanged("Deck");
     viewer.OnPropertyChanged("SelectedCard");
     Task.Factory.StartNew(
         () =>
         {
             Thread.Sleep(0);
             viewer.Dispatcher.BeginInvoke(new Action(
                 () =>
                 {
                     viewer.FilterChanged(viewer._filter);
                 }));
         });
     
 }
Пример #15
0
 private static void IsOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
 {
     var view = dependencyObject as PNSearchView;
       if (view != null && e.NewValue != e.OldValue && (bool)e.NewValue && view.searchTextBox.Focusable) {
     view.searchTextBox.Focus();
       }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewToViewModelMappingContainer"/> class.
        /// </summary>
        /// <param name="dependencyObject">The dependency object.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="dependencyObject"/> is <c>null</c>.</exception>
        public ViewToViewModelMappingContainer(DependencyObject dependencyObject)
        {
            Argument.IsNotNull("dependencyObject", dependencyObject);

            var properties = dependencyObject.GetType().GetPropertiesEx();
            foreach (var property in properties)
            {
                object[] viewToViewModelAttributes = property.GetCustomAttributesEx(typeof(ViewToViewModelAttribute), false);
                if (viewToViewModelAttributes.Length > 0)
                {
                    Log.Debug("Property '{0}' is decorated with the ViewToViewModelAttribute, creating a mapping", property.Name);

                    var viewToViewModelAttribute = (ViewToViewModelAttribute)viewToViewModelAttributes[0];

                    string propertyName = property.Name;
                    string viewModelPropertyName = (string.IsNullOrEmpty(viewToViewModelAttribute.ViewModelPropertyName)) ? propertyName : viewToViewModelAttribute.ViewModelPropertyName;

                    var mapping = new ViewToViewModelMapping(propertyName, viewModelPropertyName, viewToViewModelAttribute.MappingType);

                    // Store it (in 2 dictionaries for high-speed access)
                    _viewToViewModelMappings.Add(property.Name, mapping);
                    _viewModelToViewMappings.Add(viewModelPropertyName, mapping);
                }
            }
        }
Пример #17
0
 public static void OnAttachChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
 {
     var passwordBox = sender as PasswordBox;
     if (passwordBox == null) return;
     if ((bool)e.OldValue) passwordBox.PasswordChanged -= PasswordChanged;
     if ((bool)e.NewValue) passwordBox.PasswordChanged += PasswordChanged;
 }
Пример #18
0
        private static void AttachmentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var item = d as AttachmentListBoxItem;

            if (item == null)
                return;

            if (File.Exists(item.Attachment))
            {
                item.ShortName = Path.GetFileName(item.Attachment);

                var icon = Icon.ExtractAssociatedIcon(item.Attachment);

                if (icon == null)
                    return;

                item.FileIcon = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, 
                      BitmapSizeOptions.FromEmptyOptions());

                icon.Dispose();
                GC.Collect(1);

                item.UpdateLayout();
            }
        }
Пример #19
0
 static void OnScrollOnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
 {
     var textBox = dependencyObject as TextBox;
     if (textBox == null)
     {
         return;
     }
     bool oldValue = (bool)e.OldValue, newValue = (bool)e.NewValue;
     if (newValue == oldValue)
     {
         return;
     }
     if (newValue)
     {
         textBox.Loaded += TextBoxLoaded;
         textBox.Unloaded += TextBoxUnloaded;
     }
     else
     {
         textBox.Loaded -= TextBoxLoaded;
         textBox.Unloaded -= TextBoxUnloaded;
         if (_associations.ContainsKey(textBox))
         {
             _associations[textBox].Dispose();
         }
     }
 }
Пример #20
0
 /// <summary>
 /// ValidSpinDirectionProperty property changed handler.
 /// </summary>
 /// <param name="d">ButtonSpinner that changed its ValidSpinDirection.</param>
 /// <param name="e">Event arguments.</param>
 private static void OnValidSpinDirectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     Spinner source = (Spinner)d;
     ValidSpinDirections oldvalue = (ValidSpinDirections)e.OldValue;
     ValidSpinDirections newvalue = (ValidSpinDirections)e.NewValue;
     source.OnValidSpinDirectionChanged(oldvalue, newvalue);
 }
        private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
        {
            // when the BindPassword attached property is set on a PasswordBox,
            // start listening to its PasswordChanged event

            PasswordBox box = dp as PasswordBox;

            if (box == null)
            {
                return;
            }

            bool wasBound = (bool)(e.OldValue);
            bool needToBind = (bool)(e.NewValue);

            if (wasBound)
            {
                box.PasswordChanged -= HandlePasswordChanged;
            }

            if (needToBind)
            {
                box.PasswordChanged += HandlePasswordChanged;
            }
        }
Пример #22
0
 private static void IsReadOnlyPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
 {
     if (e.OldValue != e.NewValue && e.NewValue != null) {
         var numUpDown = (NumericUpDown)dependencyObject;
         numUpDown.ToggleReadOnlyMode((bool)e.NewValue);
     }
 }
Пример #23
0
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            if (element != item)
                element.SetCurrentValue(DataContextProperty, item); //dont want to set the datacontext to itself. taken from MetroTabControl.cs

            base.PrepareContainerForItemOverride(element, item);
        }
Пример #24
0
	public override DataTemplate SelectTemplate(object item, DependencyObject container)
	{
		if (item is string)
			return (DataTemplate)((FrameworkElement)container).FindResource("TextBlockTemplate");
		
		return null;
	}
Пример #25
0
 internal static DependencyObject GetUIParentCore(DependencyObject o) 
 {
     UIElement e = o as UIElement; 
     if (e != null) 
     {
         return e.GetUIParentCore(); 
     }
     else
     {
         ContentElement ce = o as ContentElement; 
         if (ce != null)
         { 
             return ce.GetUIParentCore(); 
         }
         else 
         {
             UIElement3D e3D = o as UIElement3D;
             if (e3D != null)
             { 
                 return e3D.GetUIParentCore();
             } 
         } 
         return null;
     } 
 }
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            PhotoGroup photoGroup = item as PhotoGroup;
            if (photoGroup.IsHeadline)
            {
                return HeadlineLayoutTemplate;
            }

            if (templateCache.ContainsKey(photoGroup.ResourceId))
            {
                return LayoutTemplateByIdentifier(templateCache[photoGroup.ResourceId]);
            }

            if (photoGroup.Photos.Count == 1)
            {
                templateCache[photoGroup.ResourceId] = 1;
                return Renderer1;
            }
            else if (photoGroup.Photos.Count == 2)
            {
                templateCache[photoGroup.ResourceId] = 2;
                return Renderer2;
            }
            else if (photoGroup.Photos.Count == 3)
            {
                templateCache[photoGroup.ResourceId] = 3;
                return Renderer3;
            }

            // Default
            templateCache[photoGroup.ResourceId] = 1;
            return Renderer1;
        }
Пример #27
0
 private static void OnAutoSizeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
 {
     var behavior = GetOrSetBehavior(sender);
     var element = (FrameworkElement)sender;
     behavior._owner = sender;
     element.Loaded += behavior.Element_Loaded;
 }
Пример #28
0
        private static void OnPanelContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                ParentPanel item = d as ParentPanel;
                ICleanup oldValue = e.OldValue as ICleanup;

                if (oldValue != null)
                {
                    oldValue.Cleanup();
                    oldValue = null;
                }
                if (e.NewValue != null)
                {
                    item.ParentContent.Content = null;

                    item.ParentContent.Content = e.NewValue;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #29
0
        /// <summary>
        /// Gets the value of the <strong>MultiBindings</strong> attached property from a given 
        /// <see cref="DependencyObject"/> object.
        /// </summary>
        /// <param name="obj">The object from which to read the property value.</param>
        /// <return>The value of the <strong>MultiBindings</strong> attached property.</return>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="obj"/> is <see langword="null"/>.
        /// </exception>
        public static MultiBindings GetMultiBindings(DependencyObject obj)
        {
            if (obj == null)
            throw new ArgumentNullException("obj");

              return (MultiBindings)obj.GetValue(MultiBindingsProperty);
        }
Пример #30
0
        private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //Add an entry to the group name collection
            var menuItem = d as MenuItem;

            if (menuItem != null)
            {
                String newGroupName = e.NewValue.ToString();
                String oldGroupName = e.OldValue.ToString();
                if (String.IsNullOrEmpty(newGroupName))
                {
                    //Removing the toggle button from grouping
                    RemoveCheckboxFromGrouping(menuItem);
                }
                else
                {
                    //Switching to a new group
                    if (newGroupName != oldGroupName)
                    {
                        if (!String.IsNullOrEmpty(oldGroupName))
                        {
                            //Remove the old group mapping
                            RemoveCheckboxFromGrouping(menuItem);
                        }
                        ElementToGroupNames.Add(menuItem, e.NewValue.ToString());
                        menuItem.Checked += MenuItemChecked;
                    }
                }
            }
        }