Exemplo n.º 1
0
 /// <summary>
 /// Creates a new XamlObjectServiceProvider instance.
 /// </summary>
 public XamlObjectServiceProvider(XamlObject obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException("obj");
     }
     XamlObject = obj;
     Resolver   = new XamlTypeResolverProvider(obj);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Gets whether shorthand XAML markup extension code can be generated for the object.
        /// </summary>
        public static bool CanPrint(XamlObject obj)
        {
            if (obj.ElementType == typeof(System.Windows.Data.MultiBinding) ||
                obj.ElementType == typeof(System.Windows.Data.PriorityBinding))
            {
                return(false);
            }

            return(CanPrint(obj, false, GetNonMarkupExtensionParent(obj)));
        }
Exemplo n.º 3
0
 void ParseObjectAttribute(XamlObject obj, XmlAttribute attribute)
 {
     try
     {
         ParseObjectAttribute(obj, attribute, true);
     }
     catch (Exception x)
     {
         ReportException(x, attribute);
     }
 }
Exemplo n.º 4
0
        static XamlProperty FindExistingXamlProperty(XamlObject obj, XamlPropertyInfo propertyInfo)
        {
            foreach (XamlProperty existing in obj.Properties)
            {
                if (existing.propertyInfo.FullyQualifiedName == propertyInfo.FullyQualifiedName)
                {
                    return(existing);
                }
            }

            throw new XamlLoadException("Existing XamlProperty " + propertyInfo.FullyQualifiedName + " not found.");
        }
Exemplo n.º 5
0
        private static XamlObject GetNonMarkupExtensionParent(XamlObject markupExtensionObject)
        {
            System.Diagnostics.Debug.Assert(markupExtensionObject.IsMarkupExtension);

            XamlObject obj = markupExtensionObject;

            while (obj != null && obj.IsMarkupExtension)
            {
                obj = obj.ParentObject;
            }
            return(obj);
        }
Exemplo n.º 6
0
        // for use by parser only
        internal XamlProperty(XamlObject parentObject, XamlPropertyInfo propertyInfo, XamlPropertyValue propertyValue)
            : this(parentObject, propertyInfo)
        {
            PossiblyNameChanged(null, propertyValue);

            this.propertyValue = propertyValue;
            if (propertyValue != null)
            {
                propertyValue.ParentProperty = this;
            }

            UpdateValueOnInstance();
        }
Exemplo n.º 7
0
 bool UpdateXmlAttribute(bool force, out XamlObject holder)
 {
     holder = FindXmlAttributeHolder();
     if (holder == null && force && IsMarkupExtension)
     {
         holder = this;
     }
     if (holder != null && MarkupExtensionPrinter.CanPrint(holder))
     {
         var s = MarkupExtensionPrinter.Print(holder);
         holder.XmlAttribute = holder.ParentProperty.SetAttribute(s);
         return(true);
     }
     return(false);
 }
Exemplo n.º 8
0
        internal XamlProperty(XamlObject parentObject, XamlPropertyInfo propertyInfo)
        {
            this.parentObject = parentObject;
            this.propertyInfo = propertyInfo;

            if (propertyInfo.IsCollection)
            {
                isCollection       = true;
                collectionElements = new CollectionElementsCollection(this);
                collectionElements.CollectionChanged += OnCollectionChanged;

                if (propertyInfo.Name.Equals(XamlConstants.ResourcesPropertyName, StringComparison.Ordinal) &&
                    propertyInfo.ReturnType == typeof(ResourceDictionary))
                {
                    isResources = true;
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the type descriptor context used for type conversions.
        /// </summary>
        /// <param name="containingObject">The containing object, used when the
        /// type descriptor context needs to resolve an XML namespace.</param>
        internal ITypeDescriptorContext GetTypeDescriptorContext(XamlObject containingObject)
        {
            IServiceProvider serviceProvider;

            if (containingObject != null)
            {
                if (containingObject.OwnerDocument != this)
                {
                    throw new ArgumentException("Containing object must belong to the document!");
                }
                serviceProvider = containingObject.ServiceProvider;
            }
            else
            {
                serviceProvider = this.ServiceProvider;
            }
            return(new DummyTypeDescriptorContext(serviceProvider));
        }
Exemplo n.º 10
0
        public XamlPropertyInfo ResolveProperty(string propertyName)
        {
            string propertyNamespace;

            if (propertyName.Contains(":"))
            {
                propertyNamespace =
                    ContainingElement.GetNamespaceOfPrefix(propertyName.Substring(0, propertyName.IndexOf(':')));
                propertyName = propertyName.Substring(propertyName.IndexOf(':') + 1);
            }
            else
            {
                propertyNamespace = ContainingElement.GetNamespaceOfPrefix("");
            }
            Type       elementType = null;
            XamlObject obj         = containingObject;

            while (obj != null)
            {
                Style style = obj.Instance as Style;
                if (style != null && style.TargetType != null)
                {
                    elementType = style.TargetType;
                    break;
                }
                obj = obj.ParentObject;
            }
            if (propertyName.Contains("."))
            {
                var allPropertiesAllowed = this.containingObject is XamlObject &&
                                           (((XamlObject)this.containingObject).ElementType == typeof(Setter) ||
                                            ((XamlObject)this.containingObject).IsMarkupExtension);
                return(XamlParser.GetPropertyInfo(document.TypeFinder, null, elementType, propertyNamespace,
                                                  propertyName, allPropertiesAllowed));
            }
            else if (elementType != null)
            {
                return(XamlParser.FindProperty(null, elementType, propertyName));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 11
0
        public object FindResource(object key)
        {
            XamlObject obj = containingObject;

            while (obj != null)
            {
                FrameworkElement el = obj.Instance as FrameworkElement;
                if (el != null)
                {
                    object val = el.Resources[key];
                    if (val != null)
                    {
                        return(val);
                    }
                }
                obj = obj.ParentObject;
            }
            return(null);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Finds the XAML namescope for the specified object and uses it to unregister the old name and then register the new name.
        /// </summary>
        /// <param name="namedObject">The object where the name was changed.</param>
        /// <param name="oldName">The old name.</param>
        /// <param name="newName">The new name.</param>
        public static void NameChanged(XamlObject namedObject, string oldName, string newName)
        {
            var obj = namedObject;

            while (obj != null)
            {
                var nameScope = GetNameScopeFromObject(obj);
                if (nameScope != null)
                {
                    if (oldName != null)
                    {
                        try
                        {
                            nameScope.UnregisterName(oldName);
                        }
                        catch (Exception x)
                        {
                            Debug.WriteLine(x.Message);
                        }
                    }
                    if (newName != null)
                    {
                        nameScope.RegisterName(newName, namedObject.Instance);

                        try
                        {
                            var prp = namedObject.ElementType.GetProperty(namedObject.RuntimeNameProperty);
                            if (prp != null)
                            {
                                prp.SetValue(namedObject.Instance, newName, null);
                            }
                        }
                        catch (Exception x)
                        {
                            Debug.WriteLine(x.Message);
                        }
                    }
                    break;
                }
                obj = obj.ParentObject;
            }
        }
Exemplo n.º 13
0
        internal static object CreateObjectFromAttributeText(string valueText, XamlPropertyInfo targetProperty,
                                                             XamlObject scope)
        {
            if (targetProperty.ReturnType == typeof(Uri))
            {
                return(scope.OwnerDocument.TypeFinder.ConvertUriToLocalUri(new Uri(valueText,
                                                                                   UriKind.RelativeOrAbsolute)));
            }
            else if (targetProperty.ReturnType == typeof(ImageSource))
            {
                var uri =
                    scope.OwnerDocument.TypeFinder.ConvertUriToLocalUri(new Uri(valueText, UriKind.RelativeOrAbsolute));
                return(targetProperty.TypeConverter.ConvertFromString(
                           scope.OwnerDocument.GetTypeDescriptorContext(scope), CultureInfo.InvariantCulture, uri.ToString()));
            }

            return(targetProperty.TypeConverter.ConvertFromString(
                       scope.OwnerDocument.GetTypeDescriptorContext(scope),
                       CultureInfo.InvariantCulture, valueText));
        }
Exemplo n.º 14
0
        private static bool IsStaticResourceThatReferencesLocalResource(XamlObject obj,
                                                                        XamlObject nonMarkupExtensionParent)
        {
            var staticResource = obj.Instance as System.Windows.StaticResourceExtension;

            if (staticResource != null && staticResource.ResourceKey != null && nonMarkupExtensionParent != null)
            {
                var parentLocalResource =
                    nonMarkupExtensionParent.ServiceProvider.Resolver.FindLocalResource(staticResource.ResourceKey);

                // If resource with the specified key is declared locally on the same object as the StaticResource is being used the markup extension
                // must be printed as element to find the resource, otherwise it will search from parent-parent and find none or another resource.
                if (parentLocalResource != null)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Removes namespace attributes defined in the root from the specified node and all child nodes.
        /// </summary>
        static void RemoveRootNamespacesFromNodeAndChildNodes(XamlObject root, XmlNode node)
        {
            foreach (XmlNode childNode in node.ChildNodes)
            {
                RemoveRootNamespacesFromNodeAndChildNodes(root, childNode);
            }

            if (node.Attributes != null)
            {
                List <XmlAttribute> removeAttributes = new List <XmlAttribute>();
                foreach (XmlAttribute attrib in node.Attributes)
                {
                    if (attrib.Name.StartsWith("xmlns:"))
                    {
                        var rootPrefix = root.OwnerDocument.GetPrefixForNamespace(attrib.Value);
                        if (rootPrefix == null)
                        {
                            //todo: check if we can add to root, (maybe same ns exists)
                            root.OwnerDocument.XmlDocument.Attributes.Append((XmlAttribute)attrib.CloneNode(true));
                            removeAttributes.Add(attrib);
                        }
                        else if (rootPrefix == attrib.Name.Substring("xmlns:".Length))
                        {
                            removeAttributes.Add(attrib);
                        }
                    }
                    else if (attrib.Name == "xmlns" && attrib.Value == XamlConstants.PresentationNamespace)
                    {
                        removeAttributes.Add(attrib);
                    }
                }
                foreach (var removeAttribute in removeAttributes)
                {
                    node.Attributes.Remove(removeAttribute);
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Method use to parse a piece of Xaml.
        /// </summary>
        /// <param name="root">The Root XamlObject of the current document.</param>
        /// <param name="xaml">The Xaml being parsed.</param>
        /// <param name="settings">Parser settings used by <see cref="XamlParser"/>.</param>
        /// <param name="parentObject">Parent Object, where the Parsed snippet will be inserted (Needed for Example for Bindings).</param>
        /// <returns>Returns the XamlObject of the parsed <paramref name="xaml"/>.</returns>
        public static XamlObject ParseSnippet(XamlObject root, string xaml, XamlParserSettings settings,
                                              XamlObject parentObject)
        {
            XmlTextReader reader  = new XmlTextReader(new StringReader(xaml));
            var           element = root.OwnerDocument.XmlDocument.ReadNode(reader);

            if (element != null)
            {
                XmlAttribute xmlnsAttribute = null;
                foreach (XmlAttribute attrib in element.Attributes)
                {
                    if (attrib.Name == "xmlns")
                    {
                        xmlnsAttribute = attrib;
                    }
                }
                if (xmlnsAttribute != null)
                {
                    element.Attributes.Remove(xmlnsAttribute);
                }

                XamlParser parser = new XamlParser();
                parser.settings          = settings;
                parser.errorSink         = (IXamlErrorSink)settings.ServiceProvider.GetService(typeof(IXamlErrorSink));
                parser.document          = root.OwnerDocument;
                parser.currentXamlObject = parentObject;
                var xamlObject = parser.ParseObject(element as XmlElement);

                RemoveRootNamespacesFromNodeAndChildNodes(root, element);

                if (xamlObject != null)
                {
                    return(xamlObject);
                }
            }
            return(null);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Method use to parse a piece of Xaml.
 /// </summary>
 /// <param name="root">The Root XamlObject of the current document.</param>
 /// <param name="xaml">The Xaml being parsed.</param>
 /// <param name="settings">Parser settings used by <see cref="XamlParser"/>.</param>
 /// <returns>Returns the XamlObject of the parsed <paramref name="xaml"/>.</returns>
 public static XamlObject ParseSnippet(XamlObject root, string xaml, XamlParserSettings settings)
 {
     return(ParseSnippet(root, xaml, settings, null));
 }
Exemplo n.º 18
0
 bool IsFirstChildResources(XamlObject obj)
 {
     return(obj.XmlElement.FirstChild != null &&
            obj.XmlElement.FirstChild.Name.EndsWith("." + XamlConstants.ResourcesPropertyName) &&
            obj.Properties.Where((prop) => prop.IsResources).FirstOrDefault() != null);
 }
Exemplo n.º 19
0
        internal static MarkupExtensionWrapper TryCreateWrapper(Type markupExtensionType, XamlObject xamlObject)
        {
            Type markupExtensionWrapperType;

            if (s_MarkupExtensionWrappers.TryGetValue(markupExtensionType, out markupExtensionWrapperType))
            {
                return(CreateWrapper(markupExtensionWrapperType, xamlObject));
            }

            return(null);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Create a XamlPropertyValue for the specified value instance.
        /// </summary>
        public XamlPropertyValue CreatePropertyValue(object instance, XamlProperty forProperty)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            Type          elementType = instance.GetType();
            TypeConverter c           = TypeDescriptor.GetConverter(instance);
            var           ctx         = new DummyTypeDescriptorContext(this.ServiceProvider);

            ctx.Instance = instance;
            bool hasStringConverter = c.CanConvertTo(ctx, typeof(string)) && c.CanConvertFrom(typeof(string));

            if (forProperty != null && hasStringConverter)
            {
                if (instance is SolidColorBrush &&
                    _colorBrushDictionary.ContainsKey(((SolidColorBrush)instance).Color))
                {
                    var name = _colorBrushDictionary[((SolidColorBrush)instance).Color];
                    return(new XamlTextValue(this, name));
                }

                return(new XamlTextValue(this, c.ConvertToInvariantString(ctx, instance)));
            }

            string ns     = GetNamespaceFor(elementType);
            string prefix = GetPrefixForNamespace(ns);

            XmlElement xml = _xmlDoc.CreateElement(prefix, elementType.Name, ns);

            if (hasStringConverter && (XamlObject.GetContentPropertyName(elementType) != null ||
                                       IsNativeType(instance)))
            {
                xml.InnerText = c.ConvertToInvariantString(instance);
            }
            else if (instance is Brush && forProperty != null)
            {
                // TODO: this is a hacky fix, because Brush Editor doesn't
                // edit Design Items and so we have no XML, only the Brush
                // object and we need to parse the Brush to XAML!
                var s = new MemoryStream();
                XamlWriter.Save(instance, s);
                s.Seek(0, SeekOrigin.Begin);
                XmlDocument doc = new XmlDocument();
                doc.Load(s);
                xml = (XmlElement)_xmlDoc.ImportNode(doc.DocumentElement, true);

                var attLst = xml.Attributes.Cast <XmlAttribute>().ToList();
                foreach (XmlAttribute att in attLst)
                {
                    if (att.Name.StartsWith(XamlConstants.Xmlns))
                    {
                        var rootAtt = doc.DocumentElement.GetAttributeNode(att.Name);
                        if (rootAtt != null && rootAtt.Value == att.Value)
                        {
                            xml.Attributes.Remove(att);
                        }
                    }
                }
            }

            return(new XamlObject(this, xml, elementType, instance));
        }
Exemplo n.º 21
0
 public BindingWrapper(XamlObject xamlObject)
     : base(xamlObject)
 {
 }
Exemplo n.º 22
0
        XamlObject ParseObject(XmlElement element)
        {
            Type elementType = settings.TypeFinder.GetType(element.NamespaceURI, element.LocalName);

            if (typeof(FrameworkTemplate).IsAssignableFrom(elementType))
            {
                var xamlObj = new XamlObject(document, element, elementType,
                                             TemplateHelper.GetFrameworkTemplate(element, currentXamlObject));
                xamlObj.ParentObject = currentXamlObject;
                return(xamlObj);
            }


            if (elementType == null)
            {
                elementType = settings.TypeFinder.GetType(element.NamespaceURI, element.LocalName + "Extension");
                if (elementType == null)
                {
                    throw new XamlLoadException("Cannot find type " + element.Name);
                }
            }

            XmlSpace   oldXmlSpace      = currentXmlSpace;
            XamlObject parentXamlObject = currentXamlObject;

            if (element.HasAttribute("xml:space"))
            {
                currentXmlSpace = (XmlSpace)Enum.Parse(typeof(XmlSpace), element.GetAttribute("xml:space"), true);
            }

            XamlPropertyInfo defaultProperty = GetDefaultProperty(elementType);

            XamlTextValue initializeFromTextValueInsteadOfConstructor = null;

            if (defaultProperty == null)
            {
                int  numberOfTextNodes = 0;
                bool onlyTextNodes     = true;
                foreach (XmlNode childNode in element.ChildNodes)
                {
                    if (childNode.NodeType == XmlNodeType.Text)
                    {
                        numberOfTextNodes++;
                    }
                    else if (childNode.NodeType == XmlNodeType.Element)
                    {
                        onlyTextNodes = false;
                    }
                }

                if (elementType == typeof(string) && numberOfTextNodes == 0)
                {
                    initializeFromTextValueInsteadOfConstructor = new XamlTextValue(document, string.Empty);
                }
                else if (onlyTextNodes && numberOfTextNodes == 1)
                {
                    foreach (XmlNode childNode in element.ChildNodes)
                    {
                        if (childNode.NodeType == XmlNodeType.Text)
                        {
                            currentParsedNode = childNode;
                            initializeFromTextValueInsteadOfConstructor = (XamlTextValue)ParseValue(childNode);
                        }
                    }
                }
            }

            currentParsedNode = element;

            object instance;

            if (initializeFromTextValueInsteadOfConstructor != null)
            {
                instance = TypeDescriptor.GetConverter(elementType)
                           .ConvertFromString(
                    document.GetTypeDescriptorContext(null),
                    CultureInfo.InvariantCulture,
                    initializeFromTextValueInsteadOfConstructor.Text);
            }
            else
            {
                instance = settings.CreateInstanceCallback(elementType, emptyObjectArray);
            }

            XamlObject obj = new XamlObject(document, element, elementType, instance);

            currentXamlObject = obj;
            obj.ParentObject  = parentXamlObject;

            if (parentXamlObject == null && obj.Instance is DependencyObject)
            {
                NameScope.SetNameScope((DependencyObject)obj.Instance, new NameScope());
            }

            ISupportInitialize iSupportInitializeInstance = instance as ISupportInitialize;

            if (iSupportInitializeInstance != null)
            {
                iSupportInitializeInstance.BeginInit();
            }

            foreach (XmlAttribute attribute in element.Attributes)
            {
                if (attribute.Value.StartsWith("clr-namespace", StringComparison.OrdinalIgnoreCase))
                {
                    // the format is "clr-namespace:<Namespace here>;assembly=<Assembly name here>"
                    var clrNamespace = attribute.Value.Split(new[] { ':', ';', '=' });
                    if (clrNamespace.Length == 4)
                    {
                        // get the assembly name
                        var assembly = settings.TypeFinder.LoadAssembly(clrNamespace[3]);
                        if (assembly != null)
                        {
                            settings.TypeFinder.RegisterAssembly(assembly);
                        }
                    }
                    else
                    {
                        // if no assembly name is there, then load the assembly of the opened file.
                        var assembly = settings.TypeFinder.LoadAssembly(null);
                        if (assembly != null)
                        {
                            settings.TypeFinder.RegisterAssembly(assembly);
                        }
                    }
                }
                if (attribute.NamespaceURI == XamlConstants.XmlnsNamespace)
                {
                    continue;
                }
                if (attribute.Name == "xml:space")
                {
                    continue;
                }
                if (GetAttributeNamespace(attribute) == XamlConstants.XamlNamespace ||
                    GetAttributeNamespace(attribute) == XamlConstants.Xaml2009Namespace)
                {
                    if (attribute.LocalName == "Name")
                    {
                        try
                        {
                            NameScopeHelper.NameChanged(obj, null, attribute.Value);
                        }
                        catch (Exception x)
                        {
                            ReportException(x, attribute);
                        }
                    }
                    continue;
                }

                ParseObjectAttribute(obj, attribute);
            }

            ParseObjectContent(obj, element, defaultProperty, initializeFromTextValueInsteadOfConstructor);

            if (iSupportInitializeInstance != null)
            {
                iSupportInitializeInstance.EndInit();
            }

            currentXmlSpace   = oldXmlSpace;
            currentXamlObject = parentXamlObject;

            return(obj);
        }
Exemplo n.º 23
0
        void ParseObjectContent(XamlObject obj, XmlElement element, XamlPropertyInfo defaultProperty,
                                XamlTextValue initializeFromTextValueInsteadOfConstructor)
        {
            bool isDefaultValueSet = false;

            XamlProperty collectionProperty        = null;
            object       collectionInstance        = null;
            Type         collectionType            = null;
            XmlElement   collectionPropertyElement = null;
            var          elementChildNodes         = GetNormalizedChildNodes(element);

            if (defaultProperty == null && obj.Instance != null &&
                CollectionSupport.IsCollectionType(obj.Instance.GetType()))
            {
                XamlObject       parentObj     = obj.ParentObject;
                var              parentElement = element.ParentNode;
                XamlPropertyInfo propertyInfo;
                if (parentObj != null)
                {
                    propertyInfo = GetPropertyInfo(settings.TypeFinder, parentObj.Instance, parentObj.ElementType,
                                                   parentElement.NamespaceURI, parentElement.LocalName);
                    collectionProperty = FindExistingXamlProperty(parentObj, propertyInfo);
                }
                collectionInstance        = obj.Instance;
                collectionType            = obj.ElementType;
                collectionPropertyElement = element;
            }
            else if (defaultProperty != null && defaultProperty.IsCollection && !element.IsEmpty)
            {
                foreach (XmlNode childNode in elementChildNodes)
                {
                    currentParsedNode = childNode;
                    XmlElement childElement = childNode as XmlElement;
                    if (childElement == null || !ObjectChildElementIsPropertyElement(childElement))
                    {
                        obj.AddProperty(collectionProperty = new XamlProperty(obj, defaultProperty));
                        collectionType     = defaultProperty.ReturnType;
                        collectionInstance = defaultProperty.GetValue(obj.Instance);
                        break;
                    }
                }
            }

            currentParsedNode = element;

            if (collectionType != null && collectionInstance == null && elementChildNodes.Count() == 1)
            {
                var firstChild = elementChildNodes.First() as XmlElement;
                if (ObjectChildElementIsCollectionInstance(firstChild, collectionType))
                {
                    collectionInstance = ParseObject(firstChild);
                    collectionProperty.PropertyValue = (XamlPropertyValue)collectionInstance;
                }
                else
                {
                    throw new XamlLoadException("Collection Instance is null");
                }
            }
            else
            {
                foreach (XmlNode childNode in elementChildNodes)
                {
                    currentParsedNode = childNode;
                    XmlElement childElement = childNode as XmlElement;
                    if (childElement != null)
                    {
                        if (childElement.NamespaceURI == XamlConstants.XamlNamespace)
                        {
                            continue;
                        }

                        if (ObjectChildElementIsPropertyElement(childElement))
                        {
                            ParseObjectChildElementAsPropertyElement(obj, childElement, defaultProperty);
                            continue;
                        }
                    }
                    if (initializeFromTextValueInsteadOfConstructor != null)
                    {
                        continue;
                    }
                    XamlPropertyValue childValue = ParseValue(childNode);
                    if (childValue != null)
                    {
                        if (collectionProperty != null)
                        {
                            collectionProperty.ParserAddCollectionElement(collectionPropertyElement, childValue);
                            CollectionSupport.AddToCollection(collectionType, collectionInstance, childValue);
                        }
                        else if (collectionProperty == null && collectionInstance is ResourceDictionary)
                        {
                            CollectionSupport.AddToCollection(collectionType, collectionInstance, childValue);
                        }
                        else
                        {
                            if (defaultProperty == null)
                            {
                                throw new XamlLoadException(
                                          "This element does not have a default value, cannot assign to it");
                            }

                            if (isDefaultValueSet)
                            {
                                throw new XamlLoadException("default property may have only one value assigned");
                            }

                            obj.AddProperty(new XamlProperty(obj, defaultProperty, childValue));
                            isDefaultValueSet = true;
                        }
                    }
                }
            }

            currentParsedNode = element;
        }
Exemplo n.º 24
0
        void ParseObjectChildElementAsPropertyElement(XamlObject obj, XmlElement element,
                                                      XamlPropertyInfo defaultProperty)
        {
            Debug.Assert(element.LocalName.Contains("."));
            // this is a element property syntax

            XamlPropertyInfo propertyInfo = GetPropertyInfo(settings.TypeFinder, obj.Instance, obj.ElementType,
                                                            element.NamespaceURI, element.LocalName);
            bool valueWasSet = false;

            object       collectionInstance = null;
            bool         isElementChildACollectionForProperty = false;
            XamlProperty collectionProperty = null;

            if (propertyInfo.IsCollection)
            {
                if (defaultProperty != null && defaultProperty.FullyQualifiedName == propertyInfo.FullyQualifiedName)
                {
                    foreach (XamlProperty existing in obj.Properties)
                    {
                        if (existing.propertyInfo == defaultProperty)
                        {
                            collectionProperty = existing;
                            break;
                        }
                    }
                }

                if (collectionProperty == null)
                {
                    obj.AddProperty(collectionProperty = new XamlProperty(obj, propertyInfo));
                }

                isElementChildACollectionForProperty =
                    IsElementChildACollectionForProperty(settings.TypeFinder, element, propertyInfo);
                if (isElementChildACollectionForProperty)
                {
                    collectionProperty.ParserSetPropertyElement((XmlElement)element.ChildNodes.Cast <XmlNode>()
                                                                .Where(x => !(x is XmlWhitespace))
                                                                .First());
                }
                else
                {
                    collectionInstance = collectionProperty.propertyInfo.GetValue(obj.Instance);
                    collectionProperty.ParserSetPropertyElement(element);
                    collectionInstance = collectionInstance ??
                                         Activator.CreateInstance(collectionProperty.propertyInfo.ReturnType);
                }
            }

            XmlSpace oldXmlSpace = currentXmlSpace;

            if (element.HasAttribute("xml:space"))
            {
                currentXmlSpace = (XmlSpace)Enum.Parse(typeof(XmlSpace), element.GetAttribute("xml:space"), true);
            }

            foreach (XmlNode childNode in element.ChildNodes)
            {
                currentParsedNode = childNode;
                XamlPropertyValue childValue = ParseValue(childNode);
                if (childValue != null)
                {
                    if (propertyInfo.IsCollection)
                    {
                        if (isElementChildACollectionForProperty)
                        {
                            collectionProperty.PropertyValue = childValue;
                        }
                        else
                        {
                            CollectionSupport.AddToCollection(propertyInfo.ReturnType, collectionInstance, childValue);
                            collectionProperty.ParserAddCollectionElement(element, childValue);
                        }
                    }
                    else
                    {
                        if (valueWasSet)
                        {
                            throw new XamlLoadException("non-collection property may have only one child element");
                        }
                        valueWasSet = true;
                        XamlProperty xp = new XamlProperty(obj, propertyInfo, childValue);
                        xp.ParserSetPropertyElement(element);
                        obj.AddProperty(xp);
                    }
                }
            }

            currentParsedNode = element;

            currentXmlSpace = oldXmlSpace;
        }
Exemplo n.º 25
0
 internal override void OnParentPropertyChanged()
 {
     parentObject = (ParentProperty != null) ? ParentProperty.ParentObject : null;
     base.OnParentPropertyChanged();
 }
Exemplo n.º 26
0
        /// <summary>
        /// Generates XAML markup extension code for the object.
        /// </summary>
        public static string Print(XamlObject obj)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("{");
            sb.Append(obj.GetNameForMarkupExtension());

            bool first      = true;
            var  properties = obj.Properties.ToList();

            if (obj.ElementType == typeof(Binding))
            {
                var p = obj.Properties.FirstOrDefault(x => x.PropertyName == "Path");
                if (p != null && p.IsSet)
                {
                    sb.Append(" ");
                    AppendPropertyValue(sb, p.PropertyValue, false);
                    properties.Remove(p);
                    first = false;
                }
            }
            else if (obj.ElementType == typeof(Reference))
            {
                var p = obj.Properties.FirstOrDefault(x => x.PropertyName == "Name");
                if (p != null && p.IsSet)
                {
                    sb.Append(" ");
                    AppendPropertyValue(sb, p.PropertyValue, false);
                    properties.Remove(p);
                    first = false;
                }
            }
            else if (obj.ElementType == typeof(StaticResourceExtension))
            {
                var p = obj.Properties.FirstOrDefault(x => x.PropertyName == "ResourceKey");
                if (p != null && p.IsSet)
                {
                    sb.Append(" ");
                    AppendPropertyValue(sb, p.PropertyValue, false);
                    properties.Remove(p);
                    first = false;
                }
            }

            foreach (var property in properties)
            {
                if (!property.IsSet)
                {
                    continue;
                }

                if (first)
                {
                    sb.Append(" ");
                }
                else
                {
                    sb.Append(", ");
                }
                first = false;

                sb.Append(property.GetNameForMarkupExtension());
                sb.Append("=");

                AppendPropertyValue(sb, property.PropertyValue, property.ReturnType == typeof(string));
            }
            sb.Append("}");
            return(sb.ToString());
        }
Exemplo n.º 27
0
        internal static object CreateObjectFromAttributeText(string valueText, Type targetType, XamlObject scope)
        {
            var converter =
                XamlNormalPropertyInfo.GetCustomTypeConverter(targetType) ??
                TypeDescriptor.GetConverter(targetType);

            return(converter.ConvertFromInvariantString(
                       scope.OwnerDocument.GetTypeDescriptorContext(scope), valueText));
        }
Exemplo n.º 28
0
 internal static MarkupExtensionWrapper CreateWrapper(Type markupExtensionWrapperType, XamlObject xamlObject)
 {
     return(Activator.CreateInstance(markupExtensionWrapperType, xamlObject) as MarkupExtensionWrapper);
 }
Exemplo n.º 29
0
 public StaticResourceWrapper(XamlObject xamlObject)
     : base(xamlObject)
 {
 }
Exemplo n.º 30
0
 /// <summary>
 /// Called by XamlParser to finish initializing the document.
 /// </summary>
 internal void ParseComplete(XamlObject rootElement)
 {
     this._rootElement = rootElement;
 }