Inheritance: INativeDependencyObjectWrapper, IRefContainer
        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;
            }
        }
        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;
                    }
                }
            }
        }
示例#3
1
 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();
         }
     }
 }
 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;
 }
示例#5
1
 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();            
 }
示例#6
1
 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;
 }
        /// <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);
        }
示例#8
1
        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);
            }
        }
示例#9
1
 /// <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);
 }
示例#10
1
 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();
       }
 }
示例#11
1
 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);
     }
 }
        /// <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);
                }
            }
        }
        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();
            }
        }
        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;
        }
示例#15
1
 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;
        }
示例#17
1
 private static void BusyCountChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     if (0.Equals(e.NewValue))
         SetIsBusy(d, false);
     else
         SetIsBusy(d, true);
 }
示例#18
1
    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();
                    }
                  });
              };
            };
        };
    }
示例#19
1
        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;
            }
        }
示例#20
1
 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);
                 }));
         });
     
 }
示例#21
1
        /// <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);
        }
示例#22
1
        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;
        }
示例#23
0
        public override System.Windows.Style SelectStyle(object item, System.Windows.DependencyObject container)
        {
            var levelCounter   = 1;
            var navigationNode = item as NavigationNode;

            if (navigationNode != null)
            {
                while (navigationNode.Parent != null)
                {
                    levelCounter++;
                    navigationNode = navigationNode.Parent;
                }

                switch (levelCounter)
                {
                case 1:
                    return(this.TopLevelStyle);

                case 2:
                    return(this.MidLevelStyle);

                case 3:
                    return(this.BottomLevelStyle);
                }
            }


            return(base.SelectStyle(item, container));
        }
示例#24
0
 public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
 {
     if (item is Parameter)
     {
         Parameter settings = item as Parameter;
         if (settings.ValueType == "ComboBoxProtease")
         {
             return(ComboBoxProtease);
         }
         else if (settings.ValueType == "Bool")
         {
             return(Bool);
         }
         else if (settings.ValueType == "ComboBoxInit")
         {
             return(ComboBoxInit);
         }
         else if (settings.ValueType == "ProductMassToleranceList")
         {
             return(ComboBoxTolerance);
         }
         else if (settings.ValueType == "TextBox")
         {
             return(TextBox);
         }
     }
     return(null);
 }
        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);
                }
            }
        }
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            //dynamic pairedItem = item;

            var valuePropertyInfo = item.GetType().GetProperty("Value");

            if (valuePropertyInfo != null)
            {
                object itemValue = valuePropertyInfo.GetGetMethod().Invoke(item, null);
                if (itemValue is String)
                {
                    return((DataTemplate)((ContentPresenter)container).FindResource("StringValueTemplate"));
                }
                else if (itemValue is IEnumerable <Encoding> )
                {
                    return((DataTemplate)((ContentPresenter)container).FindResource("EncodingValueTemplate"));
                }
                else if (itemValue is IEnumerable <string> )
                {
                    return((DataTemplate)((ContentPresenter)container).FindResource("FeatureIDColumnTemplate"));
                }
            }

            return(null);
        }
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var _item = item as FrameworkElement;

            Contract.Requires <ArgumentException>(item != null);
            return(null);
        }
示例#28
0
        private static void FindNozzlesViaTagsIntern(
            System.Windows.DependencyObject parent, Dictionary <int, Point> namedNozzles,
            string matchHead, bool extractShapes = false)
        {
            // trivial
            if (parent == null || namedNozzles == null)
            {
                return;
            }

            var toExtract = new List <UIElement>();

            // recurse visual tree
            int childrenCount = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < childrenCount; i++)
            {
                var child = System.Windows.Media.VisualTreeHelper.GetChild(parent, i);

                // deep inspect?
                var childEllipse = child as Ellipse;
                if (childEllipse != null)
                {
                    var childEllipseTagText = childEllipse.Tag as string;
                    if (childEllipseTagText != null && childEllipseTagText.Trim() != "")
                    {
                        var m = Regex.Match(childEllipseTagText, matchHead + @"#(\d+)");
                        if (m.Success)
                        {
                            var nid = Convert.ToInt32(m.Groups[1].ToString());

                            var x = Canvas.GetLeft(childEllipse) + childEllipse.Width / 2;
                            var y = Canvas.GetTop(childEllipse) + childEllipse.Height / 2;
                            if (nid > 0 && nid < 99)
                            {
                                namedNozzles[nid] = new Point(x, y);
                            }

                            // extract?
                            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                            if (extractShapes && child is UIElement)
                            {
                                toExtract.Add(child as UIElement);
                            }
                        }
                    }
                }

                // recurse?
                FindNozzlesViaTagsIntern(child, namedNozzles, matchHead, extractShapes);
            }

            if (extractShapes && parent is Canvas)
            {
                foreach (var te in toExtract)
                {
                    (parent as Canvas).Children.Remove(te);
                }
            }
        }
示例#29
0
        public static Point[] FindNozzlesViaTags(
            System.Windows.DependencyObject parent, string matchHead, bool extractShapes = false)
        {
            // find named nozzles
            var namedNozzles = new Dictionary <int, Point>();

            UIElementHelper.FindNozzlesViaTagsIntern(parent, namedNozzles, matchHead, extractShapes: extractShapes);

            // integrity check
            for (int i = 0; i < namedNozzles.Count; i++)
            {
                if (!namedNozzles.ContainsKey(1 + i))
                {
                    namedNozzles = null;
                    break;
                }
            }

            // still there
            Point[] res = null;
            if (namedNozzles != null)
            {
                res = new Point[namedNozzles.Count];
                for (int i = 0; i < namedNozzles.Count; i++)
                {
                    res[i] = namedNozzles[1 + i];
                }
            }

            return(res);
        }
示例#30
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var datatemplate = new DataTemplate();

            if (item == null)
            {
                return(datatemplate);
            }
            if (_edit)
            {
                datatemplate.VisualTree = new FrameworkElementFactory(typeof(StackPanel));
                var converter = new EnumValueConverter(item, property);
                foreach (object value in Enum.GetValues(enumType))
                {
                    var cbox = new FrameworkElementFactory(typeof(CheckBox));
                    cbox.SetValue(CheckBox.ContentProperty, value.ToString());
                    Delegate add = (RoutedEventHandler) delegate(object obj, RoutedEventArgs e) { };
                    var      b   = new Binding(property);
                    b.Converter           = converter;
                    b.ConverterParameter  = value;
                    b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                    cbox.SetValue(CheckBox.IsCheckedProperty, b);
                    cbox.AddHandler(CheckBox.CheckedEvent, add);
                    cbox.AddHandler(CheckBox.UncheckedEvent, add);
                    datatemplate.VisualTree.AppendChild(cbox);
                }
            }
            else
            {
                datatemplate.VisualTree = new FrameworkElementFactory(typeof(Label));
                datatemplate.VisualTree.SetValue(Label.ContentProperty, new Binding(property));
            }

            return(datatemplate);
        }
示例#31
0
        /// <summary>
        /// Selects a template based upon the type of the item and the
        /// corresponding template that is registered in the TemplateDictionary.
        /// </summary>
        /// <param name="item">
        /// The item to return a template for.
        /// </param>
        /// <param name="container">
        /// The parameter is not used.
        /// </param>
        /// <returns>
        /// Returns a DataTemplate for item.
        /// </returns>
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (item == null)
            {
                return(base.SelectTemplate(item, container));
            }

            Type type = item as Type ?? item.GetType();

            DataTemplate template;

            do
            {
                if (type.IsGenericType)
                {
                    type = type.GetGenericTypeDefinition();
                }

                if (this.TemplateDictionary.TryGetValue(type, out template))
                {
                    return(template);
                }

                type = type.BaseType;
            }while (type != null);

            return(base.SelectTemplate(item, container));
        }
示例#32
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            Field  field  = item as Field;
            Window window = Application.Current.MainWindow;

            if (field != null && field.Type != FieldType.Unknown)
            {
                switch (field.Type)
                {
                case FieldType.Bool:
                    return(window.FindResource("BoolFieldTemplate") as DataTemplate);

                case FieldType.Int:
                    return(window.FindResource("IntFieldTemplate") as DataTemplate);

                case FieldType.Date:
                    return(window.FindResource("DateFieldTemplate") as DataTemplate);

                case FieldType.Time:
                    return(window.FindResource("TimeFieldTemplate") as DataTemplate);

                case FieldType.Memo:
                    return(window.FindResource("MemoFieldTemplate") as DataTemplate);

                case FieldType.Separator:
                    return(window.FindResource("SeparatorFieldTemplate") as DataTemplate);

                default:
                    return(window.FindResource("PasswordFieldTemplate") as DataTemplate);
                }
            }
            return(base.SelectTemplate(item, container));
        }
示例#33
0
        public static T GetParentOfType <T>(this System.Windows.DependencyObject element) where T : System.Windows.DependencyObject
        {
            Type type = typeof(T);

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

            System.Windows.DependencyObject parent = System.Windows.Media.VisualTreeHelper.GetParent(element);

            if (parent == null &&
                ((System.Windows.FrameworkElement)element).Parent is System.Windows.DependencyObject)
            {
                parent = ((System.Windows.FrameworkElement)element).Parent;
            }

            if (parent == null)
            {
                return(null);
            }
            else if (parent.GetType() == type ||
                     parent.GetType().IsSubclassOf(type))
            {
                return(parent as T);
            }

            return(GetParentOfType <T>(parent));
        }
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var element = container as FrameworkElement;

            if (element == null || !(item is DeviceBindingViewModel))
            {
                return(null);
            }
            var deviceBindingViewModel = (DeviceBindingViewModel)item;

            switch (deviceBindingViewModel.DeviceBindingCategory)
            {
            case DeviceBindingCategory.Event:
                return(element.FindResource("EventPreview") as DataTemplate);

            case DeviceBindingCategory.Momentary:
                return(element.FindResource("MomentaryPreview") as DataTemplate);

            case DeviceBindingCategory.Range:
                return(element.FindResource("RangePreview") as DataTemplate);

            case DeviceBindingCategory.Delta:
                return(element.FindResource("DeltaPreview") as DataTemplate);

            default:
                return(null);
            }
        }
示例#35
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var itemAsLayoutContent = item as LayoutContent;

            if (item is DynamicPageEditorViewModel)
            {
                return(DynamicPageEditorTemplate);
            }

            if (item is HamburgerPageEditorViewModel)
            {
                return(HamburgerPageEditorTemplate);
            }

            if (item is ToastPageEditorViewModel)
            {
                return(HamburgerPageEditorTemplate);
            }

            //DynamicPageEditorViewModel HamburgerPageEditorViewModel ToastPageEditorViewModel is derived from PageEditorViewModel
            //So PageEditorViewModel is last one
            if (item is PageEditorViewModel)
            {
                return(PageEditorTemplate);
            }

            if (item is NoPageViewModel)
            {
                return(NoPageViewTemplate);
            }

            return(base.SelectTemplate(item, container));
        }
示例#36
0
        // Existing GetPropertyValue for the TextDecorationCollection will return the first collection, even if it is empty.
        // this skips empty collections so we can get the actual value.
        // slightly modified code from https://social.msdn.microsoft.com/Forums/vstudio/en-US/3ac626cf-60aa-427f-80e9-794f3775a70e/how-to-tell-if-richtextbox-selection-is-underlined?forum=wpf
        public static object GetRealPropertyValue(this swd.TextRange textRange, sw.DependencyProperty formattingProperty, out swd.TextRange fullRange)
        {
            object value = null;

            fullRange = null;
            var pointer = textRange.Start as swd.TextPointer;

            if (pointer != null)
            {
                var                 needsContinue = true;
                swd.TextElement     text          = null;
                sw.DependencyObject element       = pointer.Parent as swd.TextElement;
                while (needsContinue && (element is swd.Inline || element is swd.Paragraph || element is swc.TextBlock))
                {
                    value = element.GetValue(formattingProperty);
                    text  = element as swd.TextElement;
                    var seq = value as IEnumerable;
                    needsContinue = (seq == null) ? value == null : seq.Cast <object>().Count() == 0;
                    element       = element is swd.TextElement ? ((swd.TextElement)element).Parent : null;
                }
                if (text != null)
                {
                    fullRange = new swd.TextRange(text.ElementStart, text.ElementEnd);
                }
            }
            return(value);
        }
示例#37
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();
            }
        }
示例#38
0
        public override System.Windows.Style SelectStyle(object item, System.Windows.DependencyObject container)
        {
            if (item is ToolViewModel)
            {
                return(ToolStyle);
            }



            if (item is RakunFileViewModel)
            {
                LayoutDocumentItem test = container as LayoutDocumentItem;
                if (test != null)
                {
                    RakunViewerUserControl doc = new RakunViewerUserControl();
                    test.View.Content = doc;
                }
                (item as RakunFileViewModel).View = test.View.Content as RakunViewerUserControl;

                (item as RakunFileViewModel).AddModule(Workspace.This.RakunManager.startingNode);
                return(RakunStyle);
            }

            if (item is FileViewModel)
            {
                return(FileStyle);
            }

            return(base.SelectStyle(item, container));
        }
示例#39
0
        public static bool HasFocus(this sw.DependencyObject control, sw.DependencyObject focusScope, bool checkChildren = true)
        {
            var current = swi.FocusManager.GetFocusedElement(focusScope) as sw.DependencyObject;

            if (!checkChildren)
            {
                return(current == control);
            }

            // check content elements
            var ce = current as sw.ContentElement;

            while (ce != null)
            {
                current = sw.ContentOperations.GetParent(ce);
                if (current == control)
                {
                    return(true);
                }

                ce = control as sw.ContentElement;
            }

            // check visual elements
            while (current is swm.Visual || current is swm.Media3D.Visual3D)
            {
                if (current == control)
                {
                    return(true);
                }

                current = swm.VisualTreeHelper.GetParent(current);
            }
            return(false);
        }
示例#40
0
        /// <summary>
        /// Overriden base method to allow the selection of the correct DataTemplate
        /// </summary>
        /// <param name="item">The item for which the template should be retrieved</param>
        /// <param name="container">The object containing the current item</param>
        /// <returns>The <see cref="DataTemplate"/> to use when rendering the <paramref name="item"/></returns>
        public override System.Windows.DataTemplate SelectTemplate(object item,
                                                                   System.Windows.DependencyObject container)
        {
            //This should ensure that the item we are getting is in fact capable of holding our property
            //before we attempt to retrieve it.
            if (!(container is UIElement))
            {
                return(base.SelectTemplate(item, container));
            }

            //First, we gather all the templates associated with the current control through our dependency property
            TemplateCollection templates = GetTemplates(container as UIElement);

            if (templates == null || templates.Count == 0)
            {
                base.SelectTemplate(item, container);
            }

            //Then we go through them checking if any of them match our criteria
            foreach (var template in templates)
            {
                //In this case, we are checking whether the type of the item
                //is the same as the type supported by our DataTemplate
                if (template.Value.IsInstanceOfType(item))
                {
                    //And if it is, then we return that DataTemplate
                    return(template.DataTemplate);
                }
            }

            //If all else fails, then we go back to using the default DataTemplate
            return(base.SelectTemplate(item, container));
        }
示例#41
0
 public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
 {
     //FrameworkElement element = container as FrameworkElement;
     //Window w = (Window)element.Parent;
     Console.WriteLine("Selector");
     return(Window.FindResource("TreeViewDriveDataTemplate") as DataTemplate);
 }
示例#42
0
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (item is SynchronisatieViewModel)
            {
                SynchronisatieViewModel sync = item as SynchronisatieViewModel;
                switch (sync.DisplayType)
                {
                case ViewModels.Enums.SynchronisatieTypeEnum.Conflict:
                    return(ConflictTemplate);

                case ViewModels.Enums.SynchronisatieTypeEnum.GarantieConflict:
                    return(GarantieConflictTemplate);

                case ViewModels.Enums.SynchronisatieTypeEnum.Naloop:
                    return(NaloopTemplate);

                case ViewModels.Enums.SynchronisatieTypeEnum.Gelijkstart:
                    return(GelijkstartTemplate);

                case ViewModels.Enums.SynchronisatieTypeEnum.Voorstart:
                    return(VoorstartTemplate);
                }
            }
            return(null);
        }
示例#43
0
		public override DataTemplate SelectTemplate(object item, DependencyObject container)
		{
			if (item is string)
				return (DataTemplate)((FrameworkElement)container).FindResource("TextBlockTemplate");
			
			return null;
		}
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var             itemAsLayoutContent = item as LayoutContent;
            IPanelViewModel vm      = item as IPanelViewModel;
            IPanelFactory   factory = vm?.ParentFactory;

            if (factory != null)
            {
                var template = new DataTemplate();
                FrameworkElementFactory spFactory = new FrameworkElementFactory(factory.ViewType);

                spFactory.SetValue(Control.DataContextProperty, vm);
                template.VisualTree = spFactory;
                return(template);
            }

            if (item is MarkerPaneViewModel)
            {
                return(MarkersPaneTemplate);
            }

            if (item is ProjectPaneViewModel)
            {
                return(ProjectPaneTemplate);
            }

            return(base.SelectTemplate(item, container));
        }
示例#45
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            EditGridCellData cell  = item as EditGridCellData;
            BaseTimelineItem titem = cell.RowData.Row as BaseTimelineItem;

            if (titem == null)
            {
                return(null);
            }
            FrameworkElement element = container as FrameworkElement;
            DataTemplate     dt      = null;

            switch (titem.Type)
            {
            case EnumDateTime.Year:
                dt = element.FindResource("YearFileX") as DataTemplate;
                break;

            case EnumDateTime.Month:
                dt = element.FindResource("MonthFileX") as DataTemplate;
                break;

            case EnumDateTime.Day:
                dt = element.FindResource("DayFileX") as DataTemplate;
                break;
            }
            return(dt);
        }
示例#46
0
        public static void BindLocalizedString(string key, System.Windows.DependencyObject dependencyObject, object targetProperty)
        {
            string       arg_05_0     = string.Empty;
            LocExtension locExtension = new LocExtension(key);

            locExtension.SetBinding(dependencyObject, targetProperty);
        }
示例#47
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (item != null && item is MultiPayItemViewModel)
            {
                MultiPayItemViewModel multiPayViewModel = item as MultiPayItemViewModel;

                switch (multiPayViewModel.PayItem.Mode)
                {
                case Models.PosModels.PayMode.StoredValueCard:
                    return(StoredValueCardTpl);

                case Models.PosModels.PayMode.UnionPayCTPOSM:
                    return(UnionPayTpl);

                case Models.PosModels.PayMode.RongHeDynamicQRCodePay:
                    return(RongHeDynamicQRCodePayTpl);

                case Models.PosModels.PayMode.RongHeCustomerDynamicQRCodePay:
                    return(RongHeCustomerDynamicQRCodePayTpl);

                default:
                    return(PayDefaultTpl);
                }
            }
            return(null);
        }
        public static void ChartViewModelChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            var control = d as ChartControl;

            if (d == null)
            {
                throw new Exception("Unknown control type");
            }

            var old = e.OldValue as ChartViewModel;

            if (old != null)
            {
                old.ValidChartDataFound -= control.ChartViewModel_ValidChartDataFound;
                old.StartRefreshing     -= control.ChartViewModel_StartRefreshing;
            }

            var newV = e.NewValue as ChartViewModel;

            if (newV != null)
            {
                newV.ValidChartDataFound          += control.ChartViewModel_ValidChartDataFound;
                newV.StartRefreshing              += control.ChartViewModel_StartRefreshing;
                control.MainChart.DataContext      = newV;
                control.ButtonPallette.DataContext = newV;
                if (control.Visibility == Visibility.Visible)
                {
                    control.Activate();
                }
            }
        }
示例#49
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
        }
示例#50
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (!(item is DominionBase.Cards.CardSetting))
            {
                return(StringTemplate);
            }

            Type objectType = (item as DominionBase.Cards.CardSetting).Value.GetType();

            if (objectType == typeof(String))
            {
                return(StringTemplate);
            }

            else if (objectType == typeof(Boolean))
            {
                return(BooleanTemplate);
            }

            else if (objectType == typeof(int))
            {
                return(IntTemplate);
            }

            else if (objectType == typeof(DominionBase.Cards.ConstraintCollection))
            {
                return(ConstraintTemplate);
            }

            return(StringTemplate);
        }
示例#51
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var itemAsLayoutContent = item as LayoutContent;

            if (item is FileViewModel)
            {
                return(FileViewTemplate);
            }

            if (item is StartPageViewModel)
            {
                return(StartPageViewTemplate);
            }

            if (item is FileStatsViewModel)
            {
                return(FileStatsViewTemplate);
            }

            if (item is RecentFilesViewModel)
            {
                return(RecentFilesViewTemplate);
            }

            return(base.SelectTemplate(item, container));
        }
示例#52
0
        public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            var type = (Enums.WindowViewType)item;

            switch (type)
            {
            case AMing.SettingsExtensions.Enums.WindowViewType.Bottom:
                return(this.Bottom);

            case AMing.SettingsExtensions.Enums.WindowViewType.Top:
                return(this.Top);

            case AMing.SettingsExtensions.Enums.WindowViewType.Left:
                return(this.Left);

            case AMing.SettingsExtensions.Enums.WindowViewType.Right:
                return(this.Right);

            case AMing.SettingsExtensions.Enums.WindowViewType.Split:
                return(this.Split);

            case AMing.SettingsExtensions.Enums.WindowViewType.Tabs:
                return(this.Tabs);

            default:
                break;
            }
            return(base.SelectTemplate(item, container));
        }
示例#53
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);
        }
        /// <summary>
        /// Determines the matching view for a specific given type of viewmodel.
        /// </summary>
        /// <param name="item">Identifies the viewmodel object for which we require an associated view.</param>
        /// <param name="container">Identifies the container's instance that wants to resolve this association.</param>
        public override System.Windows.DataTemplate SelectTemplate(object item,
                                                                   System.Windows.DependencyObject container)
        {
            var itemAsLayoutContent = item as LayoutContent;

            if (item is FileViewModel)
            {
                return(FileViewTemplate);
            }

            if (item is FileStatsViewModel)
            {
                return(FileStatsViewTemplate);
            }

            if (item is ColorPickerViewModel)
            {
                return(ColorPickerViewTemplate);
            }

            if (item is Tool1_ViewModel || item is Tool2_ViewModel || item is Tool3_ViewModel)
            {
                return(Tooln_ViewTemplate);
            }

            return(base.SelectTemplate(item, container));
        }
 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 System.Windows.Style SelectStyle(object item, System.Windows.DependencyObject container)
        {
            GridViewGroupFooterCell      cell           = container as GridViewGroupFooterCell;
            GridViewGroupFooterRow       groupFooterRow = cell.ParentRow as GridViewGroupFooterRow;
            QueryableCollectionViewGroup group          = groupFooterRow.Group as QueryableCollectionViewGroup;

            if (group != null)
            {
                AggregateFunction f = cell.Column.AggregateFunctions.FirstOrDefault();
                if (f != null)
                {
                    AggregateResult result = group.AggregateResults[f.FunctionName];

                    if (result != null && result.Value != null && object.Equals(result.Value.GetType(), typeof(double)) && (double)result.Value > 5)
                    {
                        return(this.GroupFooterCellStyle);
                    }
                    else
                    {
                        return(this.DefaultGroupFooterCellStyle);
                    }
                }
            }

            return(new Style(typeof(GridViewGroupFooterCell)));
        }
示例#57
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;
 }
示例#58
0
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            if (!DesignerProperties.GetIsInDesignMode(container))
            {
                Window window = Application.Current.MainWindow;

                CustomNode node = item as CustomNode;
                if (node != null)
                {
                    return(window.FindResource("bcBreadcrumbItemTemplate") as DataTemplate);
                }

                Category category = item as Category;
                if (category != null)
                {
                    return(window.FindResource("bcCategoryItemTemplate") as DataTemplate);
                }

                Folder folder = item as Folder;
                if (folder != null)
                {
                    return(window.FindResource("bcFolderItemTemplate") as DataTemplate);
                }
            }


            return(base.SelectTemplate(item, container));
        }
示例#59
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);
        }
示例#60
0
 protected override void OnVisualParentChanged(DO oldParent)
 {
     if (VisualParent is FE p)
     {
         p.Loaded += (s, e) => bind(p);
     }
 }