예제 #1
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver typeResolver = (IXamlTypeResolver)serviceProvider.GetService(typeof(IXamlTypeResolver));
            int sepindex = TypeName.IndexOf('+');

            if (sepindex < 0)
            {
                return(typeResolver.Resolve(TypeName));
            }
            else
            {
                Type outerType = typeResolver.Resolve(TypeName.Substring(0, sepindex));
                return(outerType.Assembly.GetType(outerType.FullName + "+" + TypeName.Substring(sepindex + 1)));
            }
        }
예제 #2
0
 public override object ProvideValue(IServiceProvider serviceProvider)
 {
     if (this._type == null)
     {
         if (this._typeName == null)
         {
             throw new InvalidOperationException(System.Xaml.SR.Get("MarkupExtensionTypeName"));
         }
         if (serviceProvider == null)
         {
             throw new ArgumentNullException("serviceProvider");
         }
         IXamlTypeResolver service = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
         if (service == null)
         {
             throw new InvalidOperationException(System.Xaml.SR.Get("MarkupExtensionNoContext", new object[] { base.GetType().Name, "IXamlTypeResolver" }));
         }
         this._type = service.Resolve(this._typeName);
         if (this._type == null)
         {
             throw new InvalidOperationException(System.Xaml.SR.Get("MarkupExtensionTypeNameBad", new object[] { this._typeName }));
         }
     }
     return(this._type);
 }
예제 #3
0
        public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
        {
            IXamlTypeResolver resolver = context.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (value is String)
            {
                String[]    stringArray = ((String)value).Split(',');
                List <Type> types       = new List <Type>();

                for (Int32 i = 0; i < stringArray.Length; i++)
                {
                    // Try to resolve type using XAML resolver.
                    Type type = resolver.Resolve(stringArray[i].Trim());

                    // Try to resolve using Type class.
                    if (type == null)
                    {
                        type = Type.GetType(stringArray[i].Trim());
                    }

                    if (type == null)
                    {
                        throw new InvalidOperationException();
                    }
                    else
                    {
                        types.Add(type);
                    }
                }
                return(types);
            }

            return(null);
        }
예제 #4
0
        /// <summary>
        /// Returns an object that should be set on the property where this extension is applied.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>The object value to set on the property where the markup extension provided
        /// value is evaluated.</returns>
        /// <exception cref="System.InvalidOperationException">serviceProvider was null, or failed to
        /// implement a required service.</exception>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            object obj = null;
            Type   typeToResolve;

            if (_dataContextType == null)
            {
                typeToResolve = typeof(object);
            }
            else if (_dataContextType is Type)
            {
                typeToResolve = (Type)_dataContextType;
            }
            else if (_dataContextType is String)
            {
#if !WINDOWS_UWP
                // ReSharper disable SuggestUseVarKeywordEvident
                IXamlTypeResolver service = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                // ReSharper restore SuggestUseVarKeywordEvident

                typeToResolve = BindHelper.ResolveTypeByName((string)_dataContextType);

                if ((service != null) && (typeToResolve == null))
                {
                    typeToResolve = service.Resolve((string)_dataContextType);
                }
#else
                typeToResolve = BindHelper.ResolveTypeByName((string)_dataContextType);
#endif
            }
            else
            {
                throw new ArgumentNullException("LocateDataContext - DataContextType can be 'Type' or 'String' or empty.");
            }

            // ReSharper disable SuggestUseVarKeywordEvident
            IProvideValueTarget serviceProvideValueTarget = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            // ReSharper restore SuggestUseVarKeywordEvident
            if ((serviceProvideValueTarget != null) && (serviceProvideValueTarget.TargetObject != null))
            {
                // Save targets for case delayed processing
                TargetObject   = serviceProvideValueTarget.TargetObject;
                TargetProperty = serviceProvideValueTarget.TargetProperty;

                if (!(serviceProvideValueTarget.TargetObject is DependencyObject))
                {
                    throw new AggregateException("LocateDataContext - Target of the markup extension must be the DependencyObject type.");
                }
                obj = BindHelper.LocateValidDependencyPropertyByAllTrees(serviceProvideValueTarget.TargetObject as DependencyObject, FrameworkElement.DataContextProperty, MethodName, PropertyName, null, typeToResolve);
                if (obj == null)
                {
                    var frameworkElement = TargetObject as FrameworkElement;
                    if (frameworkElement != null)
                    {
                        frameworkElement.Loaded += DelayLocateDataContext;
                    }
                }
            }
            return(obj);
        }
예제 #5
0
        public override object ProvideValue(IServiceProvider provider)
        {
            if (type != null)
            {
                return(type);
            }

            if (provider == null)
            {
                throw new ArgumentNullException();
            }

            if (typeName == null)
            {
                throw new ArgumentNullException();
            }

            IXamlTypeResolver resolver = provider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (resolver == null)
            {
                throw new Exception("null resolver");
            }

            return(resolver.Resolve(typeName));
        }
예제 #6
0
        private NotNullType TypeFromName(IXamlTypeResolver xamlTypeResolver, string name)
        {
            string      AssemblyQualifiedName = Contract.NullSupressed(xamlTypeResolver.Resolve(name).AssemblyQualifiedName);
            NotNullType Result = NotNullType.GetType(AssemblyQualifiedName);

            return(Result);
        }
예제 #7
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            object obj2;

            if (this._member == null)
            {
                throw new InvalidOperationException(System.Xaml.SR.Get("MarkupExtensionStaticMember"));
            }
            Type   memberType = this.MemberType;
            string str        = null;
            string str2       = null;

            if (memberType != null)
            {
                str  = this._member;
                str2 = memberType.FullName + "." + this._member;
            }
            else
            {
                str2 = this._member;
                int index = this._member.IndexOf('.');
                if (index < 0)
                {
                    throw new ArgumentException(System.Xaml.SR.Get("MarkupExtensionBadStatic", new object[] { this._member }));
                }
                string qualifiedTypeName = this._member.Substring(0, index);
                if (qualifiedTypeName == string.Empty)
                {
                    throw new ArgumentException(System.Xaml.SR.Get("MarkupExtensionBadStatic", new object[] { this._member }));
                }
                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider");
                }
                IXamlTypeResolver service = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                if (service == null)
                {
                    throw new ArgumentException(System.Xaml.SR.Get("MarkupExtensionNoContext", new object[] { base.GetType().Name, "IXamlTypeResolver" }));
                }
                memberType = service.Resolve(qualifiedTypeName);
                str        = this._member.Substring(index + 1, (this._member.Length - index) - 1);
                if (str == string.Empty)
                {
                    throw new ArgumentException(System.Xaml.SR.Get("MarkupExtensionBadStatic", new object[] { this._member }));
                }
            }
            if (memberType.IsEnum)
            {
                return(Enum.Parse(memberType, str));
            }
            if (!this.GetFieldOrPropertyValue(memberType, str, out obj2))
            {
                throw new ArgumentException(System.Xaml.SR.Get("MarkupExtensionBadStatic", new object[] { str2 }));
            }
            return(obj2);
        }
예제 #8
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (xamlTypeResolver == null)
            {
                throw new ArgumentException("xamlTypeResolver");
            }

            Type resolvedType = xamlTypeResolver.Resolve(TypeName);

            return(resolvedType);
        }
예제 #9
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string text = value as string;

            if (context != null && text != null)
            {
                IXamlTypeResolver xamlTypeResolver = (IXamlTypeResolver)context.GetService(typeof(IXamlTypeResolver));
                if (xamlTypeResolver != null)
                {
                    return(xamlTypeResolver.Resolve(text));
                }
            }
            return(base.ConvertFrom(context, culture, value));
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string qualifiedTypeName = value as string;

            if ((context != null) && (qualifiedTypeName != null))
            {
                IXamlTypeResolver service = GetService <IXamlTypeResolver>(context);
                if (service != null)
                {
                    return(service.Resolve(qualifiedTypeName));
                }
            }
            return(base.ConvertFrom(context, culture, value));
        }
예제 #11
0
        //Utility helper to get the required information from the parserContext
        private Type GetTypeFromContext(ITypeDescriptorContext context, string typeName)
        {
            // Parser Context must exist to get the namespace info from prefix, if not, we assume it is known command.
            if (null != context && typeName != null)
            {
                IXamlTypeResolver xamlTypeResolver = (IXamlTypeResolver)context.GetService(typeof(IXamlTypeResolver));

                if (null != xamlTypeResolver)
                {
                    return(xamlTypeResolver.Resolve(typeName));
                }
            }
            return(null);
        }
예제 #12
0
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver resolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (resolver == null)
            {
                return(null);
            }
            var type = resolver.Resolve(Type);

            var s = Application.Current.Resources[type.FullName] as Style;

            return(s);
        }
예제 #13
0
 private Type parseType(IServiceProvider serviceProvider)
 {
     if (this.Type == null)
     {
         IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
         if (xamlTypeResolver != null)
         {
             return(xamlTypeResolver.Resolve(this.TypeName));
         }
     }
     else
     {
         return(this.Type);
     }
     return(typeof(IEnumerable <object>));
 }
예제 #14
0
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string typeName = value as string;

            if (null != context && typeName != null)
            {
                IXamlTypeResolver xamlTypeResolver = (IXamlTypeResolver)context.GetService(typeof(IXamlTypeResolver));

                if (null != xamlTypeResolver)
                {
                    return(xamlTypeResolver.Resolve(typeName));
                }
            }

            return(base.ConvertFrom(context, culture, value));
        }
예제 #15
0
 public Type Resolve(IServiceProvider p)
 {
     if (_type == null)
     {
         if (_typeName == null)
         {
             throw new InvalidOperationException("MarkupExtension Type requires Type or TypeName to be defined.");
         }
         IXamlTypeResolver service = p.GetService <IXamlTypeResolver>(true);
         _type = service.Resolve(_typeName);
         if (_type == null)
         {
             throw new InvalidOperationException(String.Format("MarkupExtension invalid TypeName '{0}'.", _typeName));
         }
     }
     return(_type);
 }
예제 #16
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException();
            }

            if (member == null)
            {
                throw new ArgumentNullException();
            }

            IXamlTypeResolver resolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (resolver == null)
            {
                throw new ArgumentException("Markup extension 'StaticExtension' requires 'IXamlTypeResolver' be implemented in the IServiceProvider for ProvideValue");
            }

            int    dot        = member.LastIndexOf('.');
            string typeName   = member.Substring(0, dot);
            string memberName = member.Substring(dot + 1);

            Type type = resolver.Resolve(typeName);
            // we don't check type here for nullness, as WPF raises a NRE

            PropertyInfo pi = type.GetProperty(memberName, BindingFlags.Public | BindingFlags.Static);

            if (pi != null)
            {
                return(pi.GetValue(null, null));
            }

            FieldInfo fi = type.GetField(memberName, BindingFlags.Public | BindingFlags.Static);

            if (fi != null)
            {
                return(fi.GetValue(null));
            }

            throw new ArgumentException(string.Format("'{0}' StaticExtension value cannot be resolved to an enumeration, static field, or static property", member));
        }
예제 #17
0
        /// <summary>
        ///  Return an object that should be set on the targetObject's targetProperty
        ///  for this markup extension.  TypeExtension resolves a string into a Type
        ///  and returns it.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        ///  The object to set on this property.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            // If a type was supplied, no context nor type name are needed

            if (_type != null)
            {
                return(_type);
            }

            // Validate the initialization

            if (_typeName == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionTypeName));
            }

            // Get the IXamlTypeResolver from the service provider

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

            IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            if (xamlTypeResolver == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IXamlTypeResolver"));
            }

            // Get the type

            _type = xamlTypeResolver.Resolve(_typeName);

            if (_type == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionTypeNameBad, _typeName));
            }

            return(_type);
            // we could cash the result of type as _type, but it might cause some problems, and in theory we shouldn't need to
        }
예제 #18
0
 Type ITypeResolver.ResolveType(string type)
 {
     if (typeCache.ContainsKey(type))
     {
         return(typeCache[type]);
     }
     if (IsInDesignMode())
     {
         owner.ErrorHandler.SetError();
         return(null);
     }
     try {
         var res = xamlTypeResolver.Resolve(type);
         typeCache.Add(type, res);
         return(res);
     } catch (Exception e) {
         owner.ErrorHandler.Throw(ErrorHelper.Err004(type), e);
         return(null);
     }
 }
예제 #19
0
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (value == null)
     {
         return(null);
     }
     if (value is string)
     {
         IXamlTypeResolver xamlTypeResolver = (IXamlTypeResolver)context.GetService(typeof(IXamlTypeResolver));
         if (xamlTypeResolver == null)
         {
             throw new XamlLoadException("IXamlTypeResolver not found in type descriptor context.");
         }
         return(xamlTypeResolver.Resolve((string)value));
     }
     else
     {
         return(base.ConvertFrom(context, culture, value));
     }
 }
예제 #20
0
 public override object ProvideValue(IServiceProvider serviceProvider)
 {
     if (_type == null)
     {
         if (_typeName == null)
         {
             throw new InvalidOperationException();
         }
         if (serviceProvider == null)
         {
             throw new ArgumentNullException("serviceProvider");
         }
         IXamlTypeResolver service = serviceProvider.GetService <IXamlTypeResolver>(true);
         _type = service.Resolve(_typeName);
         if (_type == null)
         {
             throw new InvalidOperationException(String.Format("Markup Type: {0} not found.", _typeName));
         }
     }
     return(_type);
 }
 public override Object ProvideValue(IServiceProvider serviceProvider)
 {
     if (Type == null)
     {
         if (String.IsNullOrWhiteSpace(TypeName))
         {
             throw new InvalidOperationException("No TypeName or Type specified.");
         }
         if (serviceProvider == null)
         {
             return(DependencyProperty.UnsetValue);
         }
         IXamlTypeResolver resolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
         if (resolver == null)
         {
             return(DependencyProperty.UnsetValue);
         }
         Type = resolver.Resolve(TypeName);
     }
     return(Type);
 }
예제 #22
0
        /// <summary>
        /// Returns an object that is provided as the value of the target property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">A service provider helper that can provide services for the markup extension.</param>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            Debug.Assert(serviceProvider != null);
            Debug.Assert(TypeName != null);
            Debug.Assert((Arg1 == null && Arg2 == null) || (Arg1 != null && Arg2 == null) || (Arg1 != null && Arg2 != null));

            IXamlTypeResolver XamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;

            System.Type Type = null;

            if (Arg1 == null && Arg2 == null)
            {
                Type = XamlTypeResolver.Resolve(TypeName);
            }

            else if (Arg1 != null && Arg2 == null)
            {
                System.Type Arg1Type;
                System.Type GenericDefinitionType;

                Arg1Type = XamlTypeResolver.Resolve(Arg1);
                GenericDefinitionType = XamlTypeResolver.Resolve($"{TypeName}`1");

                System.Type[] GenericArguments = new System.Type[] { Arg1Type };
                Type = GenericDefinitionType.MakeGenericType(GenericArguments);
            }
            else if (Arg1 != null && Arg1 != null)
            {
                System.Type Arg1Type;
                System.Type Arg2Type;
                System.Type GenericDefinitionType;

                Arg1Type = XamlTypeResolver.Resolve(Arg1);
                Arg2Type = XamlTypeResolver.Resolve(Arg2);

                GenericDefinitionType = XamlTypeResolver.Resolve(TypeName);
                Assembly GenericDefinitionAssembly = GenericDefinitionType.Assembly;
                GenericDefinitionType = GenericDefinitionAssembly.GetType(ToFullNameWithArguments(GenericDefinitionType.Name, 2));

                System.Type[] GenericArguments = new System.Type[] { Arg1Type, Arg2Type };
                Type = GenericDefinitionType.MakeGenericType(GenericArguments);
            }

            return(Type);
        }
예제 #23
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver typeResolver = (IXamlTypeResolver)serviceProvider.GetService(typeof(IXamlTypeResolver));

            return(Lite.Generate(typeResolver.Resolve(typeName)));
        }
예제 #24
0
        // Token: 0x060007C1 RID: 1985 RVA: 0x000188E8 File Offset: 0x00016AE8
        private Type GetTypeFromName(string name, object context)
        {
            ParserContext parserContext = context as ParserContext;

            if (parserContext == null)
            {
                if (context is IServiceProvider)
                {
                    IXamlTypeResolver xamlTypeResolver = (context as IServiceProvider).GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                    if (xamlTypeResolver != null)
                    {
                        return(xamlTypeResolver.Resolve(name));
                    }
                }
                IValueSerializerContext valueSerializerContext = context as IValueSerializerContext;
                if (valueSerializerContext != null)
                {
                    ValueSerializer serializerFor = ValueSerializer.GetSerializerFor(typeof(Type), valueSerializerContext);
                    if (serializerFor != null)
                    {
                        return(serializerFor.ConvertFromString(name, valueSerializerContext) as Type);
                    }
                }
                DependencyObject dependencyObject = context as DependencyObject;
                if (dependencyObject == null)
                {
                    if (FrameworkCompatibilityPreferences.TargetsDesktop_V4_0)
                    {
                        return(null);
                    }
                    dependencyObject = new DependencyObject();
                }
                WpfSharedBamlSchemaContext bamlSharedSchemaContext = XamlReader.BamlSharedSchemaContext;
                return(bamlSharedSchemaContext.ResolvePrefixedNameWithAdditionalWpfSemantics(name, dependencyObject));
            }
            int    num = name.IndexOf(':');
            string text;

            if (num == -1)
            {
                text = string.Empty;
            }
            else
            {
                text = name.Substring(0, num).TrimEnd(new char[0]);
                name = name.Substring(num + 1).TrimStart(new char[0]);
            }
            string text2 = parserContext.XmlnsDictionary[text];

            if (text2 == null)
            {
                throw new ArgumentException(SR.Get("ParserPrefixNSProperty", new object[]
                {
                    text,
                    name
                }));
            }
            TypeAndSerializer typeOnly = parserContext.XamlTypeMapper.GetTypeOnly(text2, name);

            if (typeOnly == null)
            {
                return(null);
            }
            return(typeOnly.ObjectType);
        }
        // Token: 0x0600210C RID: 8460 RVA: 0x00097FBC File Offset: 0x000961BC
        internal static DependencyProperty ResolveProperty(IServiceProvider serviceProvider, string targetName, object source)
        {
            Type               type = null;
            string             text = null;
            DependencyProperty dependencyProperty = source as DependencyProperty;

            if (dependencyProperty != null)
            {
                return(dependencyProperty);
            }
            byte[] array;
            if ((array = (source as byte[])) != null)
            {
                Baml2006SchemaContext baml2006SchemaContext = (serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider).SchemaContext as Baml2006SchemaContext;
                if (array.Length == 2)
                {
                    short propertyId = (short)((int)array[0] | (int)array[1] << 8);
                    return(baml2006SchemaContext.GetDependencyProperty(propertyId));
                }
                using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(array)))
                {
                    type = baml2006SchemaContext.GetXamlType(binaryReader.ReadInt16()).UnderlyingType;
                    text = binaryReader.ReadString();
                    goto IL_142;
                }
            }
            string text2;

            if ((text2 = (source as string)) == null)
            {
                throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                {
                    "Property",
                    typeof(DependencyProperty).FullName
                }));
            }
            text2 = text2.Trim();
            if (text2.Contains("."))
            {
                int    num = text2.LastIndexOf('.');
                string qualifiedTypeName = text2.Substring(0, num);
                text = text2.Substring(num + 1);
                IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                type = xamlTypeResolver.Resolve(qualifiedTypeName);
            }
            else
            {
                int num2 = text2.LastIndexOf(':');
                text = text2.Substring(num2 + 1);
            }
IL_142:
            if (type == null && targetName != null)
            {
                IAmbientProvider  ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider)) as IAmbientProvider;
                XamlSchemaContext schemaContext   = (serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider).SchemaContext;
                type = DependencyPropertyConverter.GetTypeFromName(schemaContext, ambientProvider, targetName);
            }
            if (type == null)
            {
                IXamlSchemaContextProvider xamlSchemaContextProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;
                if (xamlSchemaContextProvider == null)
                {
                    throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                    {
                        "Property",
                        typeof(DependencyProperty).FullName
                    }));
                }
                XamlSchemaContext schemaContext2 = xamlSchemaContextProvider.SchemaContext;
                XamlType          xamlType       = schemaContext2.GetXamlType(typeof(Style));
                XamlType          xamlType2      = schemaContext2.GetXamlType(typeof(FrameworkTemplate));
                XamlType          xamlType3      = schemaContext2.GetXamlType(typeof(DataTemplate));
                XamlType          xamlType4      = schemaContext2.GetXamlType(typeof(ControlTemplate));
                List <XamlType>   list           = new List <XamlType>();
                list.Add(xamlType);
                list.Add(xamlType2);
                list.Add(xamlType3);
                list.Add(xamlType4);
                XamlMember       member           = xamlType.GetMember("TargetType");
                XamlMember       member2          = xamlType2.GetMember("Template");
                XamlMember       member3          = xamlType4.GetMember("TargetType");
                IAmbientProvider ambientProvider2 = serviceProvider.GetService(typeof(IAmbientProvider)) as IAmbientProvider;
                if (ambientProvider2 == null)
                {
                    throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                    {
                        "Property",
                        typeof(DependencyProperty).FullName
                    }));
                }
                AmbientPropertyValue firstAmbientValue = ambientProvider2.GetFirstAmbientValue(list, new XamlMember[]
                {
                    member,
                    member2,
                    member3
                });
                if (firstAmbientValue != null)
                {
                    if (firstAmbientValue.Value is Type)
                    {
                        type = (Type)firstAmbientValue.Value;
                    }
                    else
                    {
                        if (!(firstAmbientValue.Value is TemplateContent))
                        {
                            throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                            {
                                "Property",
                                typeof(DependencyProperty).FullName
                            }));
                        }
                        TemplateContent templateContent = firstAmbientValue.Value as TemplateContent;
                        type = templateContent.OwnerTemplate.TargetTypeInternal;
                    }
                }
            }
            if (type != null && text != null)
            {
                return(DependencyProperty.FromName(text, type));
            }
            throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
            {
                "Property",
                typeof(DependencyProperty).FullName
            }));
        }
예제 #26
0
        /// <summary>
        ///  Return an object that should be set on the targetObject's targetProperty
        ///  for this markup extension.  For a StaticExtension this is a static field
        ///  or property value.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        ///  The object to set on this property.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_member == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionStaticMember));
            }

            object value;
            Type type = MemberType;
            string fieldString = null;
            string memberFullName = null;
            if (type != null)
            {
                fieldString = _member;
                memberFullName = type.FullName + "." + _member;
            }
            else
            {
                memberFullName = _member;

                // Validate the _member

                int dotIndex = _member.IndexOf('.');
                if (dotIndex < 0)
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, _member));
                }

                // Pull out the type substring (this will include any XML prefix, e.g. "av:Button")

                string typeString = _member.Substring(0, dotIndex);
                if (string.IsNullOrEmpty(typeString))
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, _member));
                }

                // Get the IXamlTypeResolver from the service provider

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

                IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                if (xamlTypeResolver == null)
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IXamlTypeResolver"));
                }

                // Use the type resolver to get a Type instance

                type = xamlTypeResolver.Resolve(typeString);

                // Get the member name substring

                fieldString = _member.Substring(dotIndex + 1, _member.Length - dotIndex - 1);
                if (string.IsNullOrEmpty(typeString))
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, _member));
                }
            }

            // Use the built-in parser for enum types
            
            if (type.IsEnum)
            {
                return Enum.Parse(type, fieldString);
            }

            // For other types, reflect
            if (GetFieldOrPropertyValue(type, fieldString, out value))
            {
                return value;
            }
            else
            {
                throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, memberFullName));
            }
        }
예제 #27
0
        public override object ProvideValue(IServiceProvider provider)
        {
            IProvideValueTarget service = (IProvideValueTarget)provider.GetService(typeof(IProvideValueTarget));

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

            target = service.TargetObject as DependencyObject;
            dp     = service.TargetProperty as DependencyProperty;

            if (target == null || dp == null)
            {
                return(null);
            }

            if (FullPropertyName != null)
            {
                string[]          name         = FullPropertyName.Split('.');
                IXamlTypeResolver typeResolver = provider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                propertyDeclaringType = typeResolver.Resolve(name[0]);
                propertyName          = name[1];
            }

            this.propertyInfo = propertyDeclaringType.GetProperty(propertyName);
            if (this.propertyInfo != null)
            {
                isStatic = (propertyInfo as PropertyInfo).GetGetMethod().IsStatic;
            }
            else
            {
                this.propertyInfo = propertyDeclaringType.GetField(propertyName);
                if (this.propertyInfo != null)
                {
                    isStatic = (propertyInfo as FieldInfo).IsStatic;
                }
                else
                {
                    throw new ArgumentException("Could not find property " + propertyName);
                }
            }

            IOptionBindingContainer container = TryFindContainer(target as FrameworkElement);

            if (container == null)
            {
                throw new InvalidOperationException("This extension can be used in OptionPanels only!");
            }

            container.AddBinding(this);

            object instance = isStatic ? null : FetchInstance(propertyDeclaringType);

            try {
                object result = null;

                if (this.propertyInfo is PropertyInfo)
                {
                    result = (propertyInfo as PropertyInfo).GetValue(instance, null);
                }
                else
                {
                    if (this.propertyInfo is FieldInfo)
                    {
                        result = (propertyInfo as FieldInfo).GetValue(instance);
                    }
                }

                return(ConvertOnDemand(result, dp.PropertyType));
            } catch (Exception e) {
                throw new Exception("Failing to convert " + this.FullPropertyName + " to " +
                                    dp.OwnerType.Name + "." + dp.Name + " (" + dp.PropertyType + ")", e);
            }
        }
        /// <summary>
        ///  Return an object that should be set on the targetObject's targetProperty
        ///  for this markup extension.  For a StaticExtension this is a static field
        ///  or property value.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        ///  The object to set on this property.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Member == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionStaticMember));
            }

            object value;

            if (MemberType != null)
            {
                value = SystemResourceKey.GetSystemResourceKey(MemberType.Name + "." + Member);
                if (value != null)
                {
                    return(value);
                }
            }
            else
            {
                value = SystemResourceKey.GetSystemResourceKey(Member);
                if (value != null)
                {
                    return(value);
                }

                // Validate the _member

                int dotIndex = Member.IndexOf('.');
                if (dotIndex < 0)
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, Member));
                }

                // Pull out the type substring (this will include any XML prefix, e.g. "av:Button")

                string typeString = Member.Substring(0, dotIndex);
                if (typeString == string.Empty)
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionBadStatic, Member));
                }

                // Get the IXamlTypeResolver from the service provider

                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider");
                }

                IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                if (xamlTypeResolver == null)
                {
                    throw new ArgumentException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IXamlTypeResolver"));
                }

                // Use the type resolver to get a Type instance

                MemberType = xamlTypeResolver.Resolve(typeString);

                // Get the member name substring

                Member = Member.Substring(dotIndex + 1, Member.Length - dotIndex - 1);
            }

            value = CommandConverter.GetKnownControlCommand(MemberType, Member);
            if (value != null)
            {
                return(value);
            }

            return(base.ProvideValue(serviceProvider));
        }
        internal static DependencyProperty ResolveProperty(IServiceProvider serviceProvider,
                                                           string targetName, object source)
        {
            Type   type     = null;
            string property = null;

            DependencyProperty dProperty = source as DependencyProperty;

            byte[] bytes;
            String value;

            if (dProperty != null)
            {
                return(dProperty);
            }
            // If it's a byte[] we got it from BAML.  Let's resolve it using the schema context
            else if ((bytes = source as byte[]) != null)
            {
                Baml2006SchemaContext schemaContext = (serviceProvider.GetService(typeof(IXamlSchemaContextProvider))
                                                       as IXamlSchemaContextProvider).SchemaContext as Baml2006SchemaContext;

                // Array with length of 2 means its an ID for a
                // DependencyProperty in the Baml2006SchemaContext
                if (bytes.Length == 2)
                {
                    short propId = (short)(bytes[0] | (bytes[1] << 8));

                    return(schemaContext.GetDependencyProperty(propId));
                }
                else
                {
                    // Otherwise it's a string with a TypeId encoded in front
                    using (BinaryReader reader = new BinaryReader(new MemoryStream(bytes)))
                    {
                        type     = schemaContext.GetXamlType(reader.ReadInt16()).UnderlyingType;
                        property = reader.ReadString();
                    }
                }
            }
            else if ((value = source as string) != null)
            {
                value = value.Trim();
                // If it contains a . it means that it is a full name with type and property.
                if (value.Contains("."))
                {
                    // Prefixes could have .'s so we take the last one and do a type resolve against that
                    int    lastIndex = value.LastIndexOf('.');
                    string typeName  = value.Substring(0, lastIndex);
                    property = value.Substring(lastIndex + 1);

                    IXamlTypeResolver resolver = serviceProvider.GetService(typeof(IXamlTypeResolver))
                                                 as IXamlTypeResolver;
                    type = resolver.Resolve(typeName);
                }
                else
                {
                    // Only have the property name
                    // Strip prefixes if there are any, v3 essentially discards the prefix in this case
                    int lastIndex = value.LastIndexOf(':');
                    property = value.Substring(lastIndex + 1);
                }
            }
            else
            {
                throw new NotSupportedException(SR.Get(SRID.ParserCannotConvertPropertyValue, "Property", typeof(DependencyProperty).FullName));
            }

            // We got additional info from either Trigger.SourceName or Setter.TargetName
            if (type == null && targetName != null)
            {
                IAmbientProvider ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider))
                                                   as System.Xaml.IAmbientProvider;
                XamlSchemaContext schemaContext = (serviceProvider.GetService(typeof(IXamlSchemaContextProvider))
                                                   as IXamlSchemaContextProvider).SchemaContext;

                type = GetTypeFromName(schemaContext,
                                       ambientProvider, targetName);
            }

            // Still don't have a Type so we need to loop up the chain and grab either Style.TargetType,
            // DataTemplate.DataType, or ControlTemplate.TargetType
            if (type == null)
            {
                IXamlSchemaContextProvider ixscp = (serviceProvider.GetService(typeof(IXamlSchemaContextProvider))
                                                    as IXamlSchemaContextProvider);
                if (ixscp == null)
                {
                    throw new NotSupportedException(SR.Get(SRID.ParserCannotConvertPropertyValue, "Property", typeof(DependencyProperty).FullName));
                }
                XamlSchemaContext schemaContext = ixscp.SchemaContext;

                XamlType styleXType             = schemaContext.GetXamlType(typeof(Style));
                XamlType frameworkTemplateXType = schemaContext.GetXamlType(typeof(FrameworkTemplate));
                XamlType dataTemplateXType      = schemaContext.GetXamlType(typeof(DataTemplate));
                XamlType controlTemplateXType   = schemaContext.GetXamlType(typeof(ControlTemplate));

                List <XamlType> ceilingTypes = new List <XamlType>();
                ceilingTypes.Add(styleXType);
                ceilingTypes.Add(frameworkTemplateXType);
                ceilingTypes.Add(dataTemplateXType);
                ceilingTypes.Add(controlTemplateXType);

                // We don't look for DataTemplate's DataType since we want to use the TargetTypeInternal instead
                XamlMember styleTargetType           = styleXType.GetMember("TargetType");
                XamlMember templateProperty          = frameworkTemplateXType.GetMember("Template");
                XamlMember controlTemplateTargetType = controlTemplateXType.GetMember("TargetType");

                IAmbientProvider ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider))
                                                   as System.Xaml.IAmbientProvider;
                if (ambientProvider == null)
                {
                    throw new NotSupportedException(SR.Get(SRID.ParserCannotConvertPropertyValue, "Property", typeof(DependencyProperty).FullName));
                }
                AmbientPropertyValue firstAmbientValue = ambientProvider.GetFirstAmbientValue(ceilingTypes, styleTargetType,
                                                                                              templateProperty, controlTemplateTargetType);

                if (firstAmbientValue != null)
                {
                    if (firstAmbientValue.Value is Type)
                    {
                        type = (Type)firstAmbientValue.Value;
                    }
                    else if (firstAmbientValue.Value is TemplateContent)
                    {
                        TemplateContent tempContent = firstAmbientValue.Value
                                                      as TemplateContent;

                        type = tempContent.OwnerTemplate.TargetTypeInternal;
                    }
                    else
                    {
                        throw new NotSupportedException(SR.Get(SRID.ParserCannotConvertPropertyValue, "Property", typeof(DependencyProperty).FullName));
                    }
                }
            }

            if (type != null && property != null)
            {
                return(DependencyProperty.FromName(property, type));
            }

            throw new NotSupportedException(SR.Get(SRID.ParserCannotConvertPropertyValue, "Property", typeof(DependencyProperty).FullName));
        }
예제 #30
0
        /// <summary>
        /// Returns an object that should be set on the property where this extension is applied.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>The object value to set on the property where the markup extension provided
        /// value is evaluated.</returns>
        /// <exception cref="System.InvalidOperationException">serviceProvider was null, or failed to
        /// implement a required service.</exception>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            if (_serviceType == null)
            {
                // ReSharper disable NotResolvedInText
                throw new ArgumentNullException("IocBinding - ServiceType cannot be null.");
                // ReSharper restore NotResolvedInText
            }


            Type typeToResolve;

            // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull
            if (_serviceType is Type)
            // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull
            {
                typeToResolve = (Type)_serviceType;
            }
            // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull
            else if (_serviceType is string)
            // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull
            {
#if !WINDOWS_UWP
                // ReSharper disable SuggestUseVarKeywordEvident
                IXamlTypeResolver service = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
                // ReSharper restore SuggestUseVarKeywordEvident

                typeToResolve = BindHelper.ResolveTypeByName((string)_serviceType);

                if ((service != null) && (typeToResolve == null))
                {
                    typeToResolve = service.Resolve((string)_serviceType);
                }
#else
                typeToResolve = BindHelper.ResolveTypeByName((string)_serviceType);
#endif

                if (typeToResolve == null)
                {
                    throw new InvalidOperationException("IocBinding invalid  cannot resolve type - " + (string)_serviceType);
                }
            }
            else
            {
                // ReSharper disable NotResolvedInText
                throw new ArgumentNullException("IocBinding - ServiceType can be 'Type' or 'String'.");
                // ReSharper restore NotResolvedInText
            }
            if (AutoWireVmDataContext.ServiceProvider != null)
            {
                try { ResolvedResult = AutoWireVmDataContext.ServiceProvider.GetService(typeToResolve); } catch { }
                if (ResolvedResult == null)
                {
                    try { ResolvedResult = Activator.CreateInstance(typeToResolve); } catch { }
                }
            }

#if !WINDOWS_UWP
            // ReSharper disable SuggestUseVarKeywordEvident
            IProvideValueTarget valueTarget = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            // ReSharper restore SuggestUseVarKeywordEvident

            //Attached collection support
            if ((valueTarget != null) && (valueTarget.TargetObject != null) && (valueTarget.TargetObject is FakeCollection) && (valueTarget.TargetProperty == null))
            {
                return(this);
            }

            if ((valueTarget != null) && (valueTarget.TargetObject != null) && (valueTarget.TargetProperty == BindXAML.AssignPropertiesProperty))
            {
                throw new ArgumentException("IocBinding - Coding Error Direct access to attached property XAML Parser.");
            }

            //if ((valueTarget != null) && (valueTarget.TargetObject != null) && (valueTarget.TargetProperty != null) && (valueTarget.TargetProperty as MethodInfo != null))
            //{
            //    // Support for a single attached property for WPF
            //    // XAML WinRt doesn't call ProvideValue() but WPF always does call ProvideValue()
            //    // In this case if use the single attached property we have to demonstrate
            //    return this; // That should be done like that
            //}
#endif
            if (!String.IsNullOrEmpty(PropertyName))
            {
                if (ResolvedResult != null)
                {
                    var info = ResolvedResult.GetPropertyInfo(PropertyName);
                    if (info == null)
                    {
                        throw new ArgumentException("IocBinding - cannot resolve 'TargetPropertyName' property  " + PropertyName);
                    }
                    ResolvedResult = info.GetValue(ResolvedResult, null);
                }
            }
            return(ResolvedResult);
        }