Example #1
0
        private PropertyInfo getContentProperty(FE parent)
        {
            var pt = parent.GetType();
            var cp = parent.GetType().GetProperties(
                BindingFlags.Public |
                BindingFlags.Instance
                ).FirstOrDefault(i => Attribute.IsDefined(i,
                                                          typeof(ContentPropertyAttribute)));

            return(cp ?? pt.GetProperty("Content"));
        }
 // 指定したタイプのUIElementを検索して返す
 public static UIElement FindElementRecursive(FrameworkElement parent, Type targetType)
 {
     if (parent.GetType() == targetType)
     {
         return parent as UIElement;
     }
     int childCount = VisualTreeHelper.GetChildrenCount(parent);
     UIElement returnElement = null;
     if (childCount > 0)
     {
         for (int i = 0; i < childCount; i++)
         {
             Object element = VisualTreeHelper.GetChild(parent, i);
             if (element.GetType() == targetType)
             {
                 return element as UIElement;
             }
             else
             {
                 returnElement = FindElementRecursive(VisualTreeHelper.GetChild(parent, i) as FrameworkElement, targetType);
             }
         }
     }
     return returnElement;
 }
        private void FindMissionUserControls(FrameworkElement frameworkElement, List<MissionUserControl> missionUserControls)
        {
            if (frameworkElement.GetType().IsSubclassOf(typeof(MissionUserControl)) || frameworkElement.GetType() == typeof(MissionUserControl))
            {
                missionUserControls.Add((MissionUserControl)frameworkElement);
            }

            //go through children
            foreach (object logicalChild in LogicalTreeHelper.GetChildren(frameworkElement))
            {
                if (logicalChild.GetType().IsSubclassOf(typeof(FrameworkElement)))
                {
                    FindMissionUserControls((FrameworkElement)logicalChild, missionUserControls);
                }
            }
        }
 public FrameworkElementWrapper(FrameworkElement element, HereString hereString, FrameworkElementWrapper parent = null)
 {
     Element = element;
     XamlDeclaration = hereString;
     Icon = IconMappings.ContainsKey(element.GetType().Name)
         ? IconMappings[element.GetType().Name]
         : IconMappings["Element"];
     GenerateChildren();
     Parent = parent;
     EventMappings = new Dictionary<string, PsEventHandler>();
     var events = element.GetType().GetEvents();
     foreach (var eventInfo in events)
     {
         EventMappings.Add(eventInfo.Name, null);
     }
 }
        private static DataContextSubscriptionMode GetDataContextSubscriptionMode(FrameworkElement element)
        {
            var dependencyResolver = IoCConfiguration.DefaultDependencyResolver;
            var dataContextSubscriptionService = dependencyResolver.Resolve<IDataContextSubscriptionService>();

            return dataContextSubscriptionService.GetDataContextSubscriptionMode(element.GetType());
        }
Example #6
0
		private static Action GetViewCloseAction(object viewModel, FrameworkElement view, bool? dialogResult)
		{
			var viewType = view.GetType();
			var closeMethod = viewType.GetMethod("Close");

			if (closeMethod != null)
				return () =>
				{
					var isClosed = false;
					if (dialogResult != null)
					{
						var resultProperty = viewType.GetProperty("DialogResult");
						if (resultProperty != null)
						{
							resultProperty.SetValue(view, dialogResult, null);
							isClosed = true;
						}
					}

					if (!isClosed)
					{
						closeMethod.Invoke(view, null);
					}
				};

			return () => PiracRunner.GetLogger<Screen>().Info("TryClose requires a view with a Close method.");
		}
        public static List<TypeIndexAssociation> GenerateTypePath(FrameworkElement element)
        {
            List<TypeIndexAssociation> typePath = new List<TypeIndexAssociation>();
            while (element != null)
            {
                int index = 0;

                if (VisualTreeHelper.GetParent(element) != null)
                {
                    DependencyObject parent = VisualTreeHelper.GetParent(element);

                    if (parent is Panel)
                    {
                        index = ((Panel)parent).Children.IndexOf(element);
                    }
                }

                typePath.Add(new TypeIndexAssociation() { ElementType = element.GetType(), Index = index });

                element = VisualTreeHelper.GetParent(element) as FrameworkElement;
            }

            typePath.Reverse();
            return typePath;
        }
 internal void CopyValues( FrameworkElement element )
 {
     foreach( PropertyInfo prop in element.GetType().GetProperties() )
     {
         _originalValues.Add( prop.Name, prop.GetValue( element, null ) );
     }
 }
Example #9
0
 public ColorViewModel(FrameworkElement window)
 {
     Window = window;
     cmdShow = new RoutedCommand();
     CommandManager.RegisterClassCommandBinding(Window.GetType(), new CommandBinding(cmdShow, cmdShow_Click));
     FillColors();
 }
        public static IOrientationProvider InitControlPrivider(FrameworkElement control)
        {
            if (control == null)
                return null;
            if (ProviderCollection.Providers.ContainsKey(control.GetType()))
            {
                IOrientationProvider provider = typeof(IOrientationProvider).Assembly.CreateInstance(ProviderCollection.Providers[control.GetType()]) as IOrientationProvider;

                return provider;
            }
            else
            {
                IOrientationProvider provider = new ElementOrientationProvider();//如果找不到对于的Provider 则使用默认元素Provider

                return provider;
            }
        }
		public __UIElementCollection(FrameworkElement VisualParent)
		{
			var p = VisualParent as Panel;

			if (p == null)
				throw new Exception("VisualParent should be of type Panel instead of " + VisualParent.GetType().Name);


			this.InternalVisualParent = VisualParent;
		}
Example #12
0
        private void WriteElementToXml(XmlWriter writer, FrameworkElement item)
        {
            if (item == null)
            {
                return;
            }

            writer.WriteStartElement(item.GetType().ToString());
            var coordinates = item.GetCoordinatesInView(this.Automator.VisualRoot);
            var rect = item.GetRect(this.Automator.VisualRoot);
            var attributes = new Dictionary<string, string>
                                 {
                                     { "name", item.AutomationName() },
                                     { "id", item.AutomationId() },
                                     { "xname", item.Name },
                                     {
                                         "visible",
                                         item.IsUserVisible(this.Automator.VisualRoot)
                                         .ToString()
                                         .ToLowerInvariant()
                                     },
                                     { "value", item.GetText() },
                                     { "x", rect.X.ToString(CultureInfo.InvariantCulture) },
                                     { "y", rect.Y.ToString(CultureInfo.InvariantCulture) },
                                     {
                                         "width",
                                         rect.Width.ToString(CultureInfo.InvariantCulture)
                                     },
                                     {
                                         "height",
                                         rect.Height.ToString(CultureInfo.InvariantCulture)
                                     },
                                     {
                                         "clickable_point",
                                         coordinates.ToString(CultureInfo.InvariantCulture)
                                     }
                                 };
            foreach (var attribute in attributes)
            {
                writer.WriteAttributeString(attribute.Key, attribute.Value);
            }

            var children = Finder.GetChildren(item);
            if (item == this.Automator.VisualRoot)
            {
                children = children.Concat(Finder.GetPopupsChildren());
            }

            foreach (var child in children)
            {
                this.WriteElementToXml(writer, child as FrameworkElement);
            }

            writer.WriteEndElement();
        }
Example #13
0
        public AttachedBinding(DependencyObject target, FrameworkElement attachTarget,
            DependencyProperty bindingProperty, Type bindingType)
        {
            // basic checks
            if (target == null) throw new ArgumentNullException("target");
            if (attachTarget == null) throw new ArgumentNullException("attachTarget");
            if (bindingProperty == null) throw new ArgumentNullException("bindingProperty");
            if (bindingType == null) throw new ArgumentNullException("bindingType");

            // we save the reference to the source
            _target = new WeakReference(target);
            _attachTarget = new WeakReference(attachTarget);
            _bindingProperty = bindingProperty;

            // we get the default value
            object _defValue = bindingProperty.GetMetadata(bindingType).DefaultValue;

            // we attach the dp
            if (attachTarget != null)
            {
                // we create the attached property
                _attachedProperty = DependencyProperty.RegisterAttached(string.Format(DP_NAME_FROMAT, _indexer++),
                                                                        bindingType, attachTarget.GetType(),
                                                                        new PropertyMetadata(_defValue,
                                                                                             OnPropertyChanged));
            }
            else
            {
                attachTarget.Loaded += (s, e) =>
                                           {
                                               // we create the binding property
                                               _attachedProperty =
                                                   DependencyProperty.RegisterAttached(
                                                       string.Format(DP_NAME_FROMAT, _indexer++),
                                                       bindingType, attachTarget.GetType(),
                                                       new PropertyMetadata(_defValue, OnPropertyChanged));

                                               // and we if have binding then
                                               if (_binding != null) SetBinding(_binding);
                                           };
            }
        }
        public override void Present(FrameworkElement frameworkElement)
        {
            // this is really hacky - do it using attributes isnt
            var attribute = frameworkElement
                                .GetType()
                                .GetCustomAttributes(typeof (RegionAttribute), true)
                                .FirstOrDefault() as RegionAttribute;

            var regionName = attribute == null ? null : attribute.Name;
            _mainWindow.PresentInRegion(frameworkElement, regionName);
        }  
Example #15
0
 // gets the first ancestor of an element that matches a given type
 public static object GetParentOfType(FrameworkElement e, Type type)
 {
     for (; e != null; e = VisualTreeHelper.GetParent(e) as FrameworkElement)
     {
         if (e.GetType().IsAssignableFrom(type))
         {
             return e;
         }
     }
     return null;
 }
 internal static void ApplyStyle(FrameworkElement ctl)
 {
     var styledict = StyleDict;
     foreach (string key in styledict.Keys)
     {
         var style = styledict[key] as Style;
         if (style != null && style.TargetType == ctl.GetType())
         {
             ctl.Style = style;
         }
     }
 }
        internal void RestoreValues( FrameworkElement element )
        {
            foreach( PropertyInfo prop in element.GetType().GetProperties() )
            {
                object o = _originalValues[prop.Name];

                if( prop.CanWrite && o != prop.GetValue( element, null ) )
                {
                    prop.SetValue( element, o, null );
                }
            }
        }
Example #18
0
		private void setPosition(FrameworkElement element, uint x, uint y, uint w, uint h)
		{
			Canvas.SetLeft(element, x);
			Canvas.SetTop(element, y);
			element.Width = w;
			element.Height = h;

			if (element.GetType() == typeof(Label))
			{
				((Label)element).Padding = new Thickness(0, 0, 0, 0);
			}
		}
Example #19
0
        public static void RegisterForNotification([NotNull] this FrameworkElement element, string PropertyName, PropertyChangedCallback callback)
        {
            var binding = new Binding(PropertyName)
            {
                Source = element
            };
            var prop = DependencyProperty.RegisterAttached($"ListenAttached{PropertyName}",
                                                           typeof(object),
                                                           element.GetType(),
                                                           new PropertyMetadata(callback));

            element.SetBinding(prop, binding);
        }
Example #20
0
        //***********************************************************************************************************************

        //***********************************************************************************************************************
        /// <summary>
        /// Enregistre une capture de la fenêtre dans la librairie d'image.
        /// </summary>
        //-----------------------------------------------------------------------------------------------------------------------
        public static void Capture(this FrameworkElement Self)
        {
            //-------------------------------------------------------------------------------------------------------------------
            var Bitmap = new WriteableBitmap((int)Self.ActualWidth, (int)Self.ActualHeight);

            Bitmap.Render(Self, null);
            Bitmap.Invalidate();
            //-------------------------------------------------------------------------------------------------------------------

            //-------------------------------------------------------------------------------------------------------------------
            string TempName = "~FrameworkCapture";
            string FileName = System.IO.Path.GetExtension(Self.GetType().ToString()).Replace(".", "");

            var LocalStore = IsolatedStorageFile.GetUserStoreForApplication();

            //-------------------------------------------------------------------------------------------------------------------

            //-------------------------------------------------------------------------------------------------------------------
            if (LocalStore != null)
            {
                //---------------------------------------------------------------------------------------------------------------
                try
                {
                    //-----------------------------------------------------------------------------------------------------------
                    if (LocalStore.FileExists(TempName))
                    {
                        LocalStore.DeleteFile(TempName);
                    }
                    //-----------------------------------------------------------------------------------------------------------

                    //-----------------------------------------------------------------------------------------------------------
                    using (var Fs = LocalStore.CreateFile(TempName))
                    {
                        Bitmap.SaveJpeg(Fs, Bitmap.PixelWidth, Bitmap.PixelHeight, 0, 100);
                    }
                    //-----------------------------------------------------------------------------------------------------------

                    //-----------------------------------------------------------------------------------------------------------
                    using (var Fs = LocalStore.OpenFile(TempName, FileMode.Open,
                                                        FileAccess.Read))
                    { (new MediaLibrary()).SavePicture(FileName + ".jpg", Fs); }
                    //-----------------------------------------------------------------------------------------------------------
                }
                //---------------------------------------------------------------------------------------------------------------
                catch {}
                //---------------------------------------------------------------------------------------------------------------
            }
            //-------------------------------------------------------------------------------------------------------------------
        }
Example #21
0
        public override IDataTriggerCondition CreateDataTriggerCondition(FrameworkElement element)
        {
            if (Property == null)
            {
                throw new Granular.Exception("Trigger.Property cannot be null");
            }

            DependencyProperty dependencyProperty = Property.GetDependencyProperty(element.GetType());

            object resolvedValue = Value == null || dependencyProperty.PropertyType.IsInstanceOfType(Value) ? Value : TypeConverter.ConvertValue(Value.ToString(), dependencyProperty.PropertyType, XamlNamespaces.Empty, null);

            FrameworkElement source = SourceName.IsNullOrEmpty() ? element : NameScope.GetTemplateNameScope(element).FindName(SourceName) as FrameworkElement;

            return(TriggerCondition.Register(source, dependencyProperty, resolvedValue));
        }
Example #22
0
        public IDataTriggerCondition CreateTriggerCondition(FrameworkElement element)
        {
            if (Property == null)
            {
                throw new Granular.Exception("Condition.Property cannot be null");
            }

            DependencyProperty dependencyProperty = Property.GetDependencyProperty(element.GetType());

            object resolvedValue = Value == null || dependencyProperty.PropertyType.IsInstanceOfType(Value) ? Value : TypeConverter.ConvertValue(Value.ToString(), dependencyProperty.PropertyType, XamlNamespaces.Empty);

            FrameworkElement source = SourceName.IsNullOrEmpty() ? element : NameScope.GetTemplateNameScope(element).FindName(SourceName) as FrameworkElement;

            return TriggerCondition.Register(source, dependencyProperty, resolvedValue);
        }
Example #23
0
 /// <summary>Checks the templated parent against a set of rules.</summary>
 /// <param name="templatedParent">The element this template is applied to.</param>
 // Token: 0x0600038E RID: 910 RVA: 0x0000A2D4 File Offset: 0x000084D4
 protected override void ValidateTemplatedParent(FrameworkElement templatedParent)
 {
     if (templatedParent == null)
     {
         throw new ArgumentNullException("templatedParent");
     }
     if (!(templatedParent is ContentPresenter))
     {
         throw new ArgumentException(SR.Get("TemplateTargetTypeMismatch", new object[]
         {
             "ContentPresenter",
             templatedParent.GetType().Name
         }));
     }
 }
Example #24
0
        private void SetIsEnabledOfChildren(FrameworkElement element)
        {
            var readOnlyProperty = element.GetType().GetProperties()
                .FirstOrDefault(prop => prop.Name.Equals("IsReadOnly"));

            if (readOnlyProperty != null)
                readOnlyProperty.SetValue(element, this.IsReadOnly, null);

            var children = LogicalTreeHelper.GetChildren(element);
            foreach (var child in children)
            {
                if (!(child is FrameworkElement)) continue;
                SetIsEnabledOfChildren((FrameworkElement) child);
            }
        }
Example #25
0
        /// <summary>
        /// Starts tracking the provided ChildWindow.
        /// </summary>
        /// <param name="childWindow">The ChildWindow to be tracked.</param>
        public static void Track(FrameworkElement childWindow)
        {
            if (childWindow == null)
                throw new ArgumentNullException("childWindow");

            // Verify that the object is a ChildWindow or subclass
            Type windowType = childWindow.GetType();
            while (windowType != null && !String.Equals(windowType.FullName, "System.Windows.Controls.ChildWindow"))
                windowType = windowType.BaseType;

            if (windowType == null)
                throw new ArgumentException("Tracked element is not a subclass of ChildWindow", "childWindow");

            if (!s_childWindows.ContainsKey(childWindow.GetHashCode()))
                s_childWindows.Add(childWindow.GetHashCode(), new WeakReference(childWindow));
        }
        private static void AttachBehaviors(FrameworkElement frameworkElement, BehaviorCollection behaviors)
        {
            BindingOperations.SetBinding(behaviors,
                FrameworkElement.DataContextProperty,
                new Binding("DataContext") { Source = frameworkElement, });

            foreach (var behavior in behaviors)
            {
                EventInfo ei = frameworkElement.GetType().GetEvent(behavior.EventName);
                if (ei == null) return;
                Behavior preventAccessToModifiedClosureBehavior = behavior;
                ei.AddEventHandler(frameworkElement, new RoutedEventHandler((x, y) =>
                {
                    Behavior b = preventAccessToModifiedClosureBehavior;
                    b.Command.Execute(b.CommandParameter);
                }));
            }
        }
		protected override void InitializeCore(FrameworkElement source)
		{
			DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(Property, source.GetType());
			descriptor.AddValueChanged(source, (s, e) =>
			{
				CommandParameter<object> parameter = new PropertyCommandParameter<object, object>(
					CustomParameter, Property, source.GetValue(Property));

				object value = Value;
				if (descriptor.Converter.CanConvertFrom(typeof(string)))
				{
					value = descriptor.Converter.ConvertFromString(Value);
				}

				if (Equals(source.GetValue(Property), value))
					ExecuteCommand(parameter);
			});
		}
Example #28
0
        public UserSoftwareUpdate(FrameworkElement element)
        {
            FilesToUpdate = new ObservableCollection<FileImpl>();

            HasUpdateStarted = false;
            HasUpdateFinished = false;

            UpdatePrep  = new RoutedCommand();
            Update      = new RoutedCommand();
            Rollback    = new RoutedCommand();
            Cancel      = new RoutedCommand();
            Reboot      = new RoutedCommand();

            CommandManager.RegisterClassCommandBinding(element.GetType(), new CommandBinding(UpdatePrep, DoSoftwareUpdatePreparation));
            CommandManager.RegisterClassCommandBinding(element.GetType(), new CommandBinding(Update, DoSoftwareUpdate));
            CommandManager.RegisterClassCommandBinding(element.GetType(), new CommandBinding(Rollback, DoRollBack));
            CommandManager.RegisterClassCommandBinding(element.GetType(), new CommandBinding(Cancel, DoCancelUpdate));
            CommandManager.RegisterClassCommandBinding(element.GetType(), new CommandBinding(Reboot, DoSaveReboot));
        }
Example #29
0
        public void Clean(FrameworkElement target, BaseValueSource valueSource)
        {
            if (Property == null)
            {
                throw new Granular.Exception("Setter.Property cannot be null");
            }

            FrameworkElement   resolvedTarget      = GetResolvedTarget(target, TargetName, valueSource);
            DependencyProperty resolvedProperty    = Property.GetDependencyProperty(resolvedTarget.GetType());
            BaseValueSource    resolvedValueSource = GetResolvedValueSource(valueSource, resolvedTarget);

            if (IsStyleValueSource(valueSource))
            {
                resolvedTarget.ClearValue(resolvedProperty, resolvedValueSource);
            }
            else
            {
                GetInitializedValueOverlapExpression(resolvedTarget, resolvedProperty, resolvedValueSource).ClearValue(this);
            }
        }
        internal static LabelValidationMetadata ParseMetadata(FrameworkElement element, bool forceUpdate, out object entity, out BindingExpression bindingExpression)
        {
            entity = (object)null;
            bindingExpression = (BindingExpression)null;
            if (element == null)
                return (LabelValidationMetadata)null;
            if (!forceUpdate)
            {
                LabelValidationMetadata validationMetadata = element.GetValue(LabelValidationHelper.ValidationMetadataProperty) as LabelValidationMetadata;
                if (validationMetadata != null)
                    return validationMetadata;
            }
            foreach (FieldInfo fieldInfo in element.GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy))
            {
                if (fieldInfo.FieldType == typeof(DependencyProperty))
                {
                    BindingExpression bindingExpression1 = element.GetBindingExpression((DependencyProperty)fieldInfo.GetValue((object)null));
                    if (bindingExpression1 != null && bindingExpression1.ParentBinding != null && bindingExpression1.ParentBinding.Path != null)
                    {
                        entity = bindingExpression1.DataItem ?? element.DataContext;
                        if (entity != null)
                        {
                            if (bindingExpression1.ParentBinding.Mode == BindingMode.TwoWay)
                            {
                                bindingExpression = bindingExpression1;
                                break;
                            }
                            else if (bindingExpression == null || string.Compare(bindingExpression1.ParentBinding.Path.Path, bindingExpression.ParentBinding.Path.Path, StringComparison.Ordinal) < 0)
                                bindingExpression = bindingExpression1;
                        }
                    }
                }
            }

            if (bindingExpression == null)
                return null;

            LabelValidationMetadata validationMetadata1 = ParseMetadata(bindingExpression.ParentBinding.Path.Path, entity);
            element.SetValue(ValidationMetadataProperty, (object)validationMetadata1);
            return validationMetadata1;
        }
        /// <summary>
        /// Gets the metadata item applicator.
        /// </summary>
        /// <param name="frameworkElement">The framework element.</param>
        /// <param name="metadataItem">The metadata item.</param>
        /// <returns>A <see cref="Rem.Ria.Infrastructure.View.Configuration.IMetadataItemApplicator"/></returns>
        public IMetadataItemApplicator GetMetadataItemApplicator( FrameworkElement frameworkElement, IMetadataItemDto metadataItem )
        {
            IMetadataItemApplicator metadataItemApplicator = null;
            var elementTypes = GetBaseTypes ( frameworkElement.GetType () );
            foreach ( var elementType in elementTypes )
            {
                var candidateElementType = elementType;
                var metadataItemApplicators =
                    from applicator in _metadataItemApplicators
                    where applicator.FrameworkElementType == candidateElementType && applicator.MetadataItemType == metadataItem.GetType ()
                    select applicator;

                metadataItemApplicator = metadataItemApplicators.SingleOrDefault ();
                if ( metadataItemApplicator != null )
                {
                    break;
                }
            }

            return metadataItemApplicator;
        }
Example #32
0
        public void Apply(FrameworkElement target, BaseValueSource valueSource)
        {
            if (Property == null)
            {
                throw new Granular.Exception("Setter.Property cannot be null");
            }

            FrameworkElement   resolvedTarget      = GetResolvedTarget(target, TargetName, valueSource);
            DependencyProperty resolvedProperty    = Property.GetDependencyProperty(resolvedTarget.GetType());
            object             resolvedValue       = Value == null || Value is IExpressionProvider || resolvedProperty.PropertyType.IsInstanceOfType(Value) ? Value : TypeConverter.ConvertValue(Value.ToString(), resolvedProperty.PropertyType, XamlNamespaces.Empty);
            BaseValueSource    resolvedValueSource = GetResolvedValueSource(valueSource, resolvedTarget);

            if (IsStyleValueSource(valueSource)) // no need to use value overlap expression in style setters
            {
                resolvedTarget.SetValue(resolvedProperty, resolvedValue, resolvedValueSource);
            }
            else
            {
                GetInitializedValueOverlapExpression(resolvedTarget, resolvedProperty, resolvedValueSource).SetValue(this, resolvedValue);
            }
        }
		static DependencyProperty GetForegroundProperty(FrameworkElement element)
		{
			if (element is Control)
				return Control.ForegroundProperty;
			if (element is TextBlock)
				return TextBlock.ForegroundProperty;

			Type type = element.GetType();

			DependencyProperty foregroundProperty;
			if (!ForegroundProperties.Value.TryGetValue(type, out foregroundProperty))
			{
				FieldInfo field = type.GetFields(BindingFlags.Public | BindingFlags.Static).FirstOrDefault(f => f.Name == "ForegroundProperty");
				if (field == null)
					throw new ArgumentException("type is not a Foregroundable type");

				var property = (DependencyProperty)field.GetValue(null);
				ForegroundProperties.Value.TryAdd(type, property);

				return property;
			}

			return foregroundProperty;
		}
 // ----------------------------------------------------------------------
 public FrameworkElementSettings(FrameworkElement frameworkElement) :
     this(frameworkElement, frameworkElement.GetType().Name)
 {
 } // FrameworkElementSettings
Example #35
0
        public static void TaskSetLabelText(FrameworkElement fe, string route, PropertyRoute context)
        {
            DependencyProperty labelText = LabelPropertySelector.TryGetValue(fe.GetType());

            if (labelText != null && fe.NotSet(labelText))
            {
                fe.SetValue(labelText, context.PropertyInfo.NiceName());
            }
        }
Example #36
0
        public static void TaskSetTypeProperty(FrameworkElement fe, string route, PropertyRoute context)
        {
            DependencyProperty typeProperty = TypePropertySelector.TryGetValue(fe.GetType());

            if (typeProperty != null && fe.NotSet(typeProperty))
            {
                fe.SetValue(typeProperty, context.Type);
            }
        }
Example #37
0
        public static void TaskSetValueProperty(FrameworkElement fe, string route, PropertyRoute context)
        {
            DependencyProperty valueProperty = ValuePropertySelector.GetValue(fe.GetType());

            bool isReadOnly = context.PropertyRouteType == PropertyRouteType.FieldOrProperty && context.PropertyInfo.IsReadOnly() || 
                context.PropertyRouteType == PropertyRouteType.Mixin;

            if (!BindingOperations.IsDataBound(fe, valueProperty))
            {
                Binding b = new Binding(route)
                {
                    Mode = isReadOnly ? BindingMode.OneWay : BindingMode.TwoWay,
                    NotifyOnValidationError = true,
                    ValidatesOnExceptions = true,
                    ValidatesOnDataErrors = true,
                };
                fe.SetBinding(valueProperty, b);
            }
        }
Example #38
0
        //-------------------------------------------------------------------
        //
        //  Protected Methods
        //
        //-------------------------------------------------------------------

        /// <summary>
        ///     Validate against the following rules
        ///     1. Must have a non-null feTemplatedParent
        ///     2. A DataTemplate must be applied to a ContentPresenter
        /// </summary>
        protected override void ValidateTemplatedParent(FrameworkElement templatedParent)
        {
            // Must have a non-null feTemplatedParent
            if (templatedParent == null)
            {
                throw new ArgumentNullException("templatedParent");
            }

            // A DataTemplate must be applied to a ContentPresenter
            if (!(templatedParent is ContentPresenter))
            {
                throw new ArgumentException(SR.Get(SRID.TemplateTargetTypeMismatch, "ContentPresenter", templatedParent.GetType().Name));
            }
        }
Example #39
0
        void get_implicit_styles_cb(FrameworkElement fwe, ImplicitStyleMask style_mask, out IntPtr styles_array)
        {
            Type   fwe_type        = fwe.GetType();
            string fwe_type_string = fwe_type.ToString();

            Style generic_xaml_style  = null;
            Style app_resources_style = null;
            Style visual_tree_style   = null;

            if ((style_mask & ImplicitStyleMask.GenericXaml) != 0)
            {
                // start with the lowest priority, the
                // generic.xaml style, only valid for
                // controls, as it requires DefaultStyleKey.
                Control control = fwe as Control;
                if (control != null)
                {
                    Type style_key = control.DefaultStyleKey as Type;
                    if (style_key != null)
                    {
                        generic_xaml_style = GetGenericXamlStyleFor(style_key);
                    }
                }
            }

            if ((style_mask & ImplicitStyleMask.ApplicationResources) != 0)
            {
                // next try the application's resources.
                // these affect all framework elements,
                // whether inside templates or out.
                app_resources_style = (Style)Resources[fwe_type];
                if (app_resources_style == null)
                {
                    app_resources_style = (Style)Resources[fwe_type_string];
                }
            }

            if ((style_mask & ImplicitStyleMask.VisualTree) != 0)
            {
                // highest priority, the visual tree
                FrameworkElement el             = fwe;
                bool             fwe_is_control = fwe is Control;
                while (el != null)
                {
                    // if the frameworkelement was defined outside of a template and we hit a containing
                    // template (e.g. if the FWE is in the Content of a ContentControl) we need to skip
                    // the intervening elements in the visual tree, until we hit more user elements.
                    if (el.TemplateOwner != null && fwe.TemplateOwner == null)
                    {
                        el = el.TemplateOwner as FrameworkElement;
                        continue;
                    }

                    // for non-controls, we limit the implicit style scope to that of the template.
                    if (!fwe_is_control && el == fwe.TemplateOwner)
                    {
                        break;
                    }

                    visual_tree_style = (Style)el.Resources[fwe_type];
                    if (visual_tree_style != null)
                    {
                        break;
                    }
                    visual_tree_style = (Style)el.Resources[fwe_type_string];
                    if (visual_tree_style != null)
                    {
                        break;
                    }

                    el = VisualTreeHelper.GetParent(el) as FrameworkElement;
                }
            }

            styles_array = Marshal.AllocHGlobal((int)ImplicitStyleIndex.Count * IntPtr.Size);

            Marshal.WriteIntPtr(styles_array, (int)ImplicitStyleIndex.GenericXaml * IntPtr.Size, (generic_xaml_style != null) ? generic_xaml_style.native : IntPtr.Zero);
            Marshal.WriteIntPtr(styles_array, (int)ImplicitStyleIndex.ApplicationResources * IntPtr.Size, (app_resources_style != null) ? app_resources_style.native : IntPtr.Zero);
            Marshal.WriteIntPtr(styles_array, (int)ImplicitStyleIndex.VisualTree * IntPtr.Size, (visual_tree_style != null) ? visual_tree_style.native : IntPtr.Zero);
        }