public override void Bind(string xaml) { XamlParser parser = new XamlParser(xaml); parser.ParseXaml(); FieldInfo[] fields = _container.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo field in fields) { object fieldValue = field.GetValue(_container); Logger.GetInstance().WriteLine("------- " + field.Name + field.FieldType); //Logger.GetInstance().WriteLine(" INTER " + field.FieldType.GetInterfaces()[0].ToString()); if (fieldValue is IBindableWidget) { IBindableWidget widget = (IBindableWidget) fieldValue; //Logger.GetInstance().WriteLine(" ** widget ** " + widget); //widget.WidgetCore.BindObject(_bindable, xxx, yyy, BindingOptions.TwoWay); Logger.GetInstance().WriteLine(_container.Name); try { BindingMetadata metadata = parser.MetadataIndexer[field.Name]; Logger.GetInstance().WriteLine(metadata.WidgetName + "," + metadata.BindingPath); widget.WidgetCore.BindObject(_bindable, metadata.BindingPath, metadata.WidgetBindingProperty, metadata.BindingOptions); } catch (KeyNotFoundException) { Logger.GetInstance().WriteLine("The field " + field.Name + "does not have any binding metadata"); } } } }
void SetUpWithCode(string code, int offset) { textEditor.Document.Text = code; textEditor.Caret.Offset = offset; var parseInfo = textEditor.CreateParseInformation(); IProject project = MockRepository.GenerateStrictMock<IProject>(); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(textEditor.FileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(textEditor.FileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(textEditor.FileName, textEditor.Document)).WhenCalled( i => { var p = new XamlParser(); p.TaskListTokens = TaskListTokens; i.ReturnValue = p.Parse(textEditor.FileName, textEditor.Document, true, project, CancellationToken.None); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock<IFileService>()); IViewContent view = MockRepository.GenerateStrictMock<IViewContent>(); view.Stub(v => v.GetService(typeof(ITextEditor))).Return(textEditor); SD.FileService.Stub(f => f.OpenFile(textEditor.FileName, false)).Return(view); }
void SetUpWithCode(FileName fileName, ITextSource textSource) { IProject project = MockRepository.GenerateStrictMock<IProject>(); var parseInfo = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); var pc = new CSharpProjectContent().AddOrUpdateFiles(parseInfo.UnresolvedFile); pc = pc.AddAssemblyReferences(new[] { Corlib, PresentationCore, PresentationFramework, SystemXaml }); var compilation = pc.CreateCompilation(); SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>()); SD.ParserService.Stub(p => p.GetCachedParseInformation(fileName)).Return(parseInfo); SD.ParserService.Stub(p => p.GetCompilation(project)).Return(compilation); SD.ParserService.Stub(p => p.GetCompilationForFile(fileName)).Return(compilation); SD.ParserService.Stub(p => p.Parse(fileName, textSource)).WhenCalled( i => { i.ReturnValue = new XamlParser() { TaskListTokens = TaskListTokens }.Parse(fileName, textSource, true, project, CancellationToken.None); }).Return(parseInfo); // fake Return to make it work SD.Services.AddService(typeof(IFileService), MockRepository.GenerateStrictMock<IFileService>()); IViewContent view = MockRepository.GenerateStrictMock<IViewContent>(); SD.FileService.Stub(f => f.OpenFile(fileName, false)).Return(view); }
public unsafe static Value HydrateFromString (string xaml, Value *obj, bool create_namescope, bool validate_templates) { XamlParser p = new XamlParser () { CreateNameScope = create_namescope, ValidateTemplates = validate_templates, HydrateObject = Value.ToObject (null, obj), }; object v = p.ParseString (xaml); return ObjectToValue (v); }
public static Value CreateFromString (string xaml, bool create_namescope, bool validate_templates, IntPtr owner) { XamlParser p = new XamlParser () { CreateNameScope = create_namescope, ValidateTemplates = validate_templates, Owner = NativeDependencyObjectHelper.FromIntPtr (owner) }; object v = p.ParseString (xaml); return ObjectToValue (v); }
public static object ConvertObject (XamlParser parser, XamlObjectElement element, Type dest_type, TypeConverter converter, string prop_name, object val) { // Should i return default(T) if property.PropertyType is a valuetype? if (val == null) return val; if (dest_type.IsAssignableFrom (val.GetType ())) return val; if (dest_type == typeof (string)) return val.ToString (); if (converter == null || ConverterIsBlackListed (converter)) converter = new XamlTypeConverter (parser, element, prop_name, dest_type); return converter.ConvertFrom (null, Helper.DefaultCulture, val); }
public XamlObjectElement (XamlParser parser, string name, Type type, object o) : base (parser, name) { this.type = type; Object = o; }
public static object ConvertObject (XamlParser parser, XamlObjectElement element, Type dest_type, TypeConverter converter, string prop_name, object val) { // Should i return default(T) if property.PropertyType is a valuetype? if (val == null) return val; if (dest_type.IsAssignableFrom (val.GetType ())) return val; if (dest_type == typeof (string)) return val.ToString (); if (converter == null) converter = new XamlTypeConverter (parser, element, prop_name, dest_type); if (!converter.CanConvertFrom (val.GetType ())) throw new Exception (string.Format ("type converter {0} can't convert from type {1} destination type: {2}", converter.GetType (), val.GetType (), dest_type)); return converter.ConvertFrom (null, Helper.DefaultCulture, val); }
protected override void LoadInternal(OpenedFile file, System.IO.Stream stream) { wasChangedInDesigner = false; Debug.Assert(file == this.PrimaryFile); SD.AnalyticsMonitor.TrackFeature(typeof(WpfViewContent), "Load"); _stream = new MemoryStream(); stream.CopyTo(_stream); stream.Position = 0; if (designer == null) { // initialize designer on first load designer = new DesignSurface(); this.UserContent = designer; InitPropertyEditor(); InitWpfToolbox(); } this.UserContent = designer; if (outline != null) { outline.Root = null; } using (XmlTextReader r = new XmlTextReader(stream)) { XamlLoadSettings settings = new XamlLoadSettings(); settings.DesignerAssemblies.Add(typeof(WpfViewContent).Assembly); settings.CustomServiceRegisterFunctions.Add( delegate(XamlDesignContext context) { context.Services.AddService(typeof(IUriContext), new FileUriContext(this.PrimaryFile)); context.Services.AddService(typeof(IPropertyDescriptionService), new PropertyDescriptionService(this.PrimaryFile)); context.Services.AddService(typeof(IEventHandlerService), new SharpDevelopEventHandlerService(this)); context.Services.AddService(typeof(ITopLevelWindowService), new WpfAndWinFormsTopLevelWindowService()); context.Services.AddService(typeof(ChooseClassServiceBase), new IdeChooseClassService()); }); settings.TypeFinder = MyTypeFinder.Create(this.PrimaryFile); try { settings.ReportErrors = UpdateTasks; designer.LoadDesigner(r, settings); designer.DesignPanel.ContextMenuHandler = (contextMenu) => { var newContextmenu = new ContextMenu(); var sdContextMenuItems = MenuService.CreateMenuItems(newContextmenu, designer, "/AddIns/WpfDesign/Designer/ContextMenu", "ContextMenu"); foreach(var entry in sdContextMenuItems) newContextmenu.Items.Add(entry); newContextmenu.Items.Add(new Separator()); var items = contextMenu.Items.Cast<Object>().ToList(); contextMenu.Items.Clear(); foreach(var entry in items) newContextmenu.Items.Add(entry); designer.DesignPanel.ContextMenu = newContextmenu; }; if (outline != null && designer.DesignContext != null && designer.DesignContext.RootItem != null) { outline.Root = OutlineNode.Create(designer.DesignContext.RootItem); } propertyGridView.PropertyGrid.SelectedItems = null; designer.DesignContext.Services.Selection.SelectionChanged += OnSelectionChanged; designer.DesignContext.Services.GetService<UndoService>().UndoStackChanged += OnUndoStackChanged; } catch (Exception e) { this.UserContent = new WpfDocumentError(e); } try{ if (WpfEditorOptions.EnableAppXamlParsing) { var appXaml = SD.ProjectService.CurrentProject.Items.FirstOrDefault(x=>x.FileName.GetFileName().ToLower() == ("app.xaml")); if (appXaml!=null){ var f=appXaml as FileProjectItem; OpenedFile a = SD.FileService.GetOrCreateOpenedFile(f.FileName); var xml = XmlReader.Create(a.OpenRead()); var doc=new XmlDocument(); doc.Load(xml); var node = doc.FirstChild.ChildNodes.Cast<XmlNode>().FirstOrDefault(x=>x.Name=="Application.Resources"); foreach (XmlAttribute att in doc.FirstChild.Attributes.Cast<XmlAttribute>().ToList()) { if (att.Name.StartsWith("xmlns")) node.Attributes.Append(att); } var appXamlXml = XmlReader.Create(new StringReader(node.InnerXml)); var parsed = XamlParser.Parse(appXamlXml, ((XamlDesignContext) designer.DesignContext).ParserSettings); var dict = (ResourceDictionary)parsed.RootInstance; designer.DesignPanel.Resources.MergedDictionaries.Add(dict); } } } catch (Exception ex) { LoggingService.Error("Error in loading app.xaml", ex); } } }
/// <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) { 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); //Remove namespace Attributes defined in the Xaml Root from the Pasted Snippet! List<XmlAttribute> removeAttributes = new List<XmlAttribute>(); foreach (XmlAttribute attrib in element.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(6)) { removeAttributes.Add(attrib); } } } foreach (var removeAttribute in removeAttributes) { element.Attributes.Remove(removeAttribute); } //end remove XamlParser parser = new XamlParser(); parser.settings = settings; parser.document = root.OwnerDocument; var xamlObject = parser.ParseObject(element as XmlElement); if (xamlObject != null) return xamlObject; } return null; }
public void TemplateApplyTest() { string text = @" <ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name='root'> <FrameworkElement x:Name='child' Height='400'/> <ControlTemplate.Triggers> <Trigger Property='FrameworkElement.Width' Value='100'> <Setter Property='FrameworkElement.Height' Value='100'/> </Trigger> <Trigger Property='FrameworkElement.Width' Value='200'> <Setter Property='FrameworkElement.Height' Value='200'/> <Setter TargetName='child' Property='FrameworkElement.Height' Value='200'/> </Trigger> <EventTrigger RoutedEvent='FrameworkElement.Initialized'> <Setter Property='FrameworkElement.Height' Value='300'/> </EventTrigger> </ControlTemplate.Triggers> </ControlTemplate>"; ControlTemplate controlTemplate = XamlLoader.Load(XamlParser.Parse(text)) as ControlTemplate; Control control = new Control(); control.Width = 100; control.Template = controlTemplate; control.ApplyTemplate(); Assert.AreEqual(1, control.VisualChildren.Count()); FrameworkElement child1 = control.TemplateChild as FrameworkElement; Assert.IsNotNull(child1); FrameworkElement child2 = control.Template.FindName("child", control) as FrameworkElement; Assert.AreEqual(child1, child2); Assert.AreEqual(control, child1.TemplatedParent); Assert.AreEqual(400, child1.Height); Assert.AreEqual(BaseValueSource.ParentTemplate, child1.GetValueSource(FrameworkElement.HeightProperty).BaseValueSource); Assert.AreEqual(BaseValueSource.ParentTemplate, child1.GetBaseValueSource(FrameworkElement.HeightProperty)); Assert.AreEqual(100, control.Height); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetValueSource(FrameworkElement.HeightProperty).BaseValueSource); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetBaseValueSource(FrameworkElement.HeightProperty)); control.Width = 200; Assert.AreEqual(200, control.Height); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetValueSource(FrameworkElement.HeightProperty).BaseValueSource); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetBaseValueSource(FrameworkElement.HeightProperty)); Assert.AreEqual(200, child1.Height); Assert.AreEqual(BaseValueSource.ParentTemplateTrigger, child1.GetValueSource(FrameworkElement.HeightProperty).BaseValueSource); Assert.AreEqual(BaseValueSource.ParentTemplateTrigger, child1.GetBaseValueSource(FrameworkElement.HeightProperty)); control.RaiseEvent(new RoutedEventArgs(FrameworkElement.InitializedEvent, control)); Assert.AreEqual(300, control.Height); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetValueSource(FrameworkElement.HeightProperty).BaseValueSource); Assert.AreEqual(BaseValueSource.TemplateTrigger, control.GetBaseValueSource(FrameworkElement.HeightProperty)); control.Template = null; control.ApplyTemplate(); Assert.AreEqual(Double.NaN, control.Height); }
public XamlObjectElement (XamlParser parser, string name, object o) : base (parser, name) { Object = o; }
public XamlPropertyElement (XamlParser parser, string name, XamlPropertySetter setter) : base (parser, name) { Setter = setter; }
public void VisualStateStoryboardTest() { string text = @" <Control xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Width='0'> <Control.TemplateChild> <FrameworkElement> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name='StateGroup1'> <VisualStateGroup.Transitions> <VisualTransition To='State1'> <VisualTransition.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' To='100'/> </Storyboard> </VisualTransition.Storyboard> </VisualTransition> <VisualTransition To='State2'> <VisualTransition.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' To='200'/> </Storyboard> </VisualTransition.Storyboard> </VisualTransition> </VisualStateGroup.Transitions> <VisualState x:Name='State1'> <VisualState.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' From='100' To='200'/> </Storyboard> </VisualState.Storyboard> </VisualState> <VisualState x:Name='State2'> <VisualState.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' From='200' To='300'/> </Storyboard> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </FrameworkElement> </Control.TemplateChild> </Control>"; Control control = XamlLoader.Load(XamlParser.Parse(text)) as Control; VisualStateGroup group1 = VisualStateManager.GetVisualStateGroups(control.TemplateChild).FirstOrDefault(); Assert.IsTrue(group1 != null); TestRootClock rootClock = new TestRootClock(); control.SetAnimatableRootClock(new AnimatableRootClock(rootClock, true)); VisualStateManager.GoToState(control, "State1", true); rootClock.Tick(TimeSpan.FromSeconds(0)); Assert.AreEqual(0, control.Width); rootClock.Tick(TimeSpan.FromSeconds(0.5)); Assert.AreEqual(50, control.Width); rootClock.Tick(TimeSpan.FromSeconds(1)); Assert.AreEqual(100, control.Width); rootClock.Tick(TimeSpan.FromSeconds(1.5)); Assert.AreEqual(150, control.Width); VisualStateManager.GoToState(control, "State2", true); rootClock.Tick(TimeSpan.FromSeconds(2)); Assert.AreEqual(175, control.Width); rootClock.Tick(TimeSpan.FromSeconds(2.5)); Assert.AreEqual(200, control.Width); rootClock.Tick(TimeSpan.FromSeconds(3)); Assert.AreEqual(250, control.Width); rootClock.Tick(TimeSpan.FromSeconds(4)); Assert.AreEqual(300, control.Width); VisualStateManager.GoToState(control, "State1", false); rootClock.Tick(TimeSpan.FromSeconds(4)); Assert.AreEqual(100, control.Width); rootClock.Tick(TimeSpan.FromSeconds(5)); Assert.AreEqual(200, control.Width); }
private static DocumentNode ParseMarkupExtension(XamlParserContext parserContext, ITextLocation lineInformation, IDocumentNodeReference nodeReference, IXmlNamespaceResolver xmlNamespaceResolver, IType typeId, MarkupExtensionDescription description) { int count = description.PositionalArguments.Count; DocumentCompositeNode node = parserContext.DocumentContext.CreateNode((ITypeId)typeId); IDocumentNodeReference documentNodeReference = (IDocumentNodeReference) new DocumentCompositeNodeReference(nodeReference, node); IConstructor constructor1 = (IConstructor)null; if (typeId.IsResolvable) { IList <IConstructor> constructors = typeId.GetConstructors(); if (constructors.Count > 0) { int num = 0; foreach (IConstructor constructor2 in (IEnumerable <IConstructor>)constructors) { if (constructor2.Parameters.Count == count) { if (num == 0) { constructor1 = constructor2; } ++num; } } if (num == 0) { parserContext.ReportError(XamlParseErrors.IncorrectNumberOfConstructorArguments(lineInformation, (ITypeId)typeId)); } else if (num <= 1) { ; } } else { parserContext.ReportError(XamlParseErrors.NoAccessibleConstructor(lineInformation, (ITypeId)typeId)); } } DocumentNode[] documentNodeArray = constructor1 != null ? new DocumentNode[constructor1.Parameters.Count] : (DocumentNode[])null; IConstructorArgumentProperties argumentProperties = typeId.GetConstructorArgumentProperties(); if (count > 0) { for (int index = 0; index < count; ++index) { string str = description.PositionalArguments[index]; bool flag = constructor1 != null && index < constructor1.Parameters.Count; IType type = parserContext.TypeResolver.ResolveType(parserContext.TypeResolver.PlatformMetadata.KnownTypes.Object); if (flag) { IParameter parameter = constructor1.Parameters[index]; type = parserContext.TypeResolver.ResolveType((ITypeId)parameter.ParameterType); IProperty property = argumentProperties[parameter.Name]; if (property != null && !property.PropertyType.IsAssignableFrom((ITypeId)type)) { flag = false; parserContext.ReportError(XamlParseErrors.ConstructorArgumentDeclaredTypeDoesNotMatchProperty(lineInformation, (IPropertyId)property)); } } TypeConverter typeConverter = type.TypeConverter; DocumentNode propertyValue = MarkupExtensionParser.GetPropertyValue(parserContext, lineInformation, documentNodeReference, xmlNamespaceResolver, typeConverter, type, str, true); if (flag && propertyValue != null) { documentNodeArray[index] = XamlParser.CanAssignTo(parserContext, lineInformation, type, propertyValue) ? propertyValue : (DocumentNode)null; } } } node.SetConstructor(constructor1, (IList <DocumentNode>)documentNodeArray); int num1 = 0; foreach (KeyValuePair <string, string> keyValuePair in (IEnumerable <KeyValuePair <string, string> >)description.NamedArguments) { string key = keyValuePair.Key; MemberType memberTypes = MemberType.LocalProperty | MemberType.AttachedProperty | MemberType.Field; if (parserContext.TypeResolver.IsCapabilitySet(PlatformCapability.IncompleteAttachedPropertiesInMarkupExtensions)) { memberTypes |= MemberType.IncompleteAttachedProperty; } IProperty propertyKey = XamlTypeHelper.GetPropertyKey(parserContext, lineInformation, xmlNamespaceResolver, key, (XmlNamespace)null, typeId, memberTypes, MemberType.LocalProperty, false); if (propertyKey != null) { DocumentNode propertyValue = MarkupExtensionParser.GetPropertyValue(parserContext, lineInformation, documentNodeReference, xmlNamespaceResolver, propertyKey, keyValuePair.Value, true); if (propertyValue != null && XamlParser.SetProperty(parserContext, lineInformation, new DocumentCompositeNodeReference(documentNodeReference, node), (XamlSourceContext)null, (IPropertyId)propertyKey, propertyValue)) { propertyValue.ContainerSourceContext = (INodeSourceContext) new MarkupExtensionParser.MinimalSourceContext(num1++); } } } return((DocumentNode)node); }
internal static XamlDocument Parse(XmlDocument document, XamlParserSettings settings) { if (document == null) throw new ArgumentNullException("document"); if (settings == null) throw new ArgumentNullException("settings"); XamlParser p = new XamlParser(); p.settings = settings; p.errorSink = (IXamlErrorSink)settings.ServiceProvider.GetService(typeof(IXamlErrorSink)); p.document = new XamlDocument(document, settings); try { var root = p.ParseObject(document.DocumentElement); p.document.ParseComplete(root); } catch (Exception x) { p.ReportException(x, p.currentParsedNode); } return p.document; }
public ParseInformation CreateParseInformation() { var parser = new XamlParser(); return parser.Parse(this.FileName, this.Document, true, null, CancellationToken.None); }
private static void UpdateControlWithXmlData(GUIControl control, Type controlType, XmlNode pControlNode, IDictionary <string, string> defines, string filename) { List <int> vecInfo = new List <int>(); IDictionary <XMLSkinAttribute, MemberInfo> attributesThatCanBeUpdates = GetAttributesToUpdate(controlType); if (attributesThatCanBeUpdates != null) { var nodeDic = getNodes(pControlNode); foreach (KeyValuePair <XMLSkinAttribute, MemberInfo> en in attributesThatCanBeUpdates) { XMLSkinAttribute xmlAttr = (XMLSkinAttribute)en.Key; MemberInfo correspondingMemberAttr = en.Value as MemberInfo; //XmlNode elementNode = pControlNode.SelectSingleNode(xmlAttr.XmlElementName); //XmlNode elementNode = pControlNode.SelectSingleNodeFast(xmlAttr.XmlElementName); XmlNode elementNode; //if (elementNode != null) if (nodeDic.TryGetValue(xmlAttr.XmlElementName, out elementNode)) { XmlNode attribNode = elementNode.Attributes.GetNamedItem(xmlAttr.XmlAttributeName); if (attribNode != null) { if (correspondingMemberAttr != null) { string text = attribNode.Value; // Window defines (passed in) override references defines (cached). if (text.Length > 0 && text[0] == '#') { string foundDefine = null; if (defines.TryGetValue(text, out foundDefine)) { text = foundDefine; } else { if (_cachedDefines.TryGetValue(text, out foundDefine)) { text = foundDefine; } } } object newValue = null; if (correspondingMemberAttr.MemberType == MemberTypes.Field) { newValue = ConvertXmlStringToObject(xmlAttr.XmlAttributeName, text, ((FieldInfo)correspondingMemberAttr).FieldType); } else if (correspondingMemberAttr.MemberType == MemberTypes.Property) { newValue = ConvertXmlStringToObject(xmlAttr.XmlAttributeName, text, ((PropertyInfo)correspondingMemberAttr).PropertyType); } try { if (correspondingMemberAttr.MemberType == MemberTypes.Field) { ((FieldInfo)correspondingMemberAttr).SetValue(control, newValue); } else if (correspondingMemberAttr.MemberType == MemberTypes.Property) { ((PropertyInfo)correspondingMemberAttr).SetValue(control, newValue, null); } } catch (Exception e) { Log.Info("Couldn't place {0}, which is {1} in {2}. Exception:{3}", newValue, newValue.GetType(), correspondingMemberAttr, e); } } else { if (char.IsUpper(xmlAttr.XmlAttributeName[0])) { PropertyInfo propertyInfo; if (xmlAttr.XmlAttributeName.IndexOf('.') != -1) { propertyInfo = controlType.GetProperty(xmlAttr.XmlAttributeName.Split('.')[1]); } else { propertyInfo = controlType.GetProperty(xmlAttr.XmlAttributeName); } if (propertyInfo == null) { Log.Info( "GUIControlFactory.UpdateControlWithXmlData: '{0}' does not contain a definition for '{1}'", controlType, xmlAttr.XmlAttributeName); return; } } } } } } } IDictionary <string, MemberInfo> membersThatCanBeUpdated = GetMembersToUpdate(controlType); List <VisualEffect> animations = new List <VisualEffect>(); List <VisualEffect> thumbAnimations = new List <VisualEffect>(); XmlNodeList childNodes = pControlNode.ChildNodes; bool hasVisiblecondition = false; foreach (XmlNode element in childNodes) { if (element.Name == "visible") { if (element.InnerText != null) { hasVisiblecondition = true; if (element.InnerText != "yes" && element.InnerText != "no") { if (element.InnerText.Length != 0) { int iVisibleCondition = 0; bool allowHiddenFocus = false; //Add parent's visible condition in addition to ours XmlNode parentNode = pControlNode.ParentNode; if (IsGroupControl(parentNode)) { string parentVisiblecondition = GetVisibleConditionXML(parentNode); if (!string.IsNullOrEmpty(parentVisiblecondition) && parentVisiblecondition != "yes" && parentVisiblecondition != "no") { element.InnerText += "+[" + parentVisiblecondition + "]"; } } GetConditionalVisibility(element, control, ref iVisibleCondition, ref allowHiddenFocus); control.SetVisibleCondition(iVisibleCondition, allowHiddenFocus); continue; } } } } if (element.Name == "animation") { VisualEffect effect = new VisualEffect(); if (effect.Create(element)) { if (effect.AnimationType == AnimationType.VisibleChange) { effect.AnimationType = AnimationType.Visible; //if (effect.IsReversible) { VisualEffect effect2 = (VisualEffect)effect.CloneReverse(); effect2.AnimationType = AnimationType.Hidden; //animations.Add(effect); animations.Add(effect2); //continue; } } animations.Add(effect); continue; } } if (element.Name == "thumbAnimation") { VisualEffect effect = new VisualEffect(); if (effect.Create(element)) { thumbAnimations.Add(effect); continue; } } if (element.Name == "info") { List <string> infoList = new List <string>(); if (GetMultipleString(element, "info", ref infoList)) { vecInfo.Clear(); for (int i = 0; i < infoList.Count; i++) { int infoId = GUIInfoManager.TranslateString(infoList[i]); if (infoId != 0) { vecInfo.Add(infoId); } } } control.Info = vecInfo; } MemberInfo correspondingMember = null; membersThatCanBeUpdated.TryGetValue(element.Name, out correspondingMember); if (correspondingMember != null) { string text = element.InnerText; // Window defines (passed in) override references defines (cached). if (text.Length > 0 && text[0] == '#') { string foundDefine = null; if (defines.TryGetValue(text, out foundDefine)) { text = foundDefine; } else { if (_cachedDefines.TryGetValue(text, out foundDefine)) { text = foundDefine; } } } object newValue = null; if (correspondingMember.MemberType == MemberTypes.Field) { newValue = ConvertXmlStringToObject(element.Name, text, ((FieldInfo)correspondingMember).FieldType); } else if (correspondingMember.MemberType == MemberTypes.Property) { newValue = ConvertXmlStringToObject(element.Name, text, ((PropertyInfo)correspondingMember).PropertyType); } try { if (correspondingMember.MemberType == MemberTypes.Field) { ((FieldInfo)correspondingMember).SetValue(control, newValue); } else if (correspondingMember.MemberType == MemberTypes.Property) { ((PropertyInfo)correspondingMember).SetValue(control, newValue, null); } } catch (Exception e) { Log.Info("Couldn't place {0}, which is {1} in {2}. Exception:{3}", newValue, newValue.GetType(), correspondingMember, e); } } else { if (char.IsUpper(element.Name[0])) { PropertyInfo propertyInfo; if (element.Name.IndexOf('.') != -1) { propertyInfo = controlType.GetProperty(element.Name.Split('.')[1]); } else { propertyInfo = controlType.GetProperty(element.Name); } if (propertyInfo == null) { Log.Info("GUIControlFactory.UpdateControlWithXmlData: '{0}' does not contain a definition for '{1}'", controlType, element.Name); return; } string xml = element.OuterXml; if (xml.IndexOf("Button.") != -1) { xml = xml.Replace("Button.", "GUIControl."); } else if (xml.IndexOf("Window.") != -1) { xml = xml.Replace("Window.", "GUIWindow."); } XamlParser.LoadXml(xml, XmlNodeType.Element, control, filename); } } } //Set parent control's visible condition as ours wn if we're children of a group if (!hasVisiblecondition) { XmlNode parentNode = pControlNode.ParentNode; if (IsGroupControl(parentNode)) { XmlDocument tempDoc = new XmlDocument(); XmlNode elem = tempDoc.CreateElement("visible"); int iVisibleCondition = 0; bool allowHiddenFocus = true; string parentVisiblecondition = GetVisibleConditionXML(parentNode); if (!string.IsNullOrEmpty(parentVisiblecondition) && parentVisiblecondition != "yes" && parentVisiblecondition != "no") { elem.InnerText = parentVisiblecondition; XmlNode visibleNode = pControlNode.OwnerDocument.ImportNode(elem, true); pControlNode.AppendChild(visibleNode); GetConditionalVisibility(visibleNode, control, ref iVisibleCondition, ref allowHiddenFocus); control.SetVisibleCondition(iVisibleCondition, allowHiddenFocus); } } } if (animations.Count > 0) { control.SetAnimations(animations); } if (thumbAnimations.Count > 0) { control.SetThumbAnimations(thumbAnimations); } }
public XamlPropertyElement (XamlParser parser, string name, XamlPropertySetter setter) : base (parser, name) { Setter = setter; DetermineIfSetOnAdd (); }
internal void crunch (XmlTextReader reader) { int justClosed = 0; XamlParser p = new XamlParser(reader); XamlNode n; while (true) { n = p.GetNextNode(); if (n == null) break; Debug.WriteLine(this.GetType() + ": INCOMING " + n.GetType()); if (n is XamlDocumentStartNode) { Debug.WriteLine(this.GetType() + ": document begins"); // do nothing } else if (n is XamlElementStartNode && n.Depth == 0) { Debug.WriteLine(this.GetType() + ": element begins as top-level"); CreateTopLevel(((XamlElementStartNode)n).ElementType, ((XamlElementStartNode)n).name); } else if (n is XamlElementStartNode && ((XamlElementStartNode)n).propertyObject) { Debug.WriteLine(this.GetType() + ": element begins as property value"); string key = getKeyFromNode(n); CreatePropertyObject(((XamlElementStartNode)n).ElementType, ((XamlElementStartNode)n).name, key); } else if (n is XamlElementStartNode && ((XamlElementStartNode)n).depPropertyObject) { Debug.WriteLine(this.GetType() + ": element begins as dependency property value"); string key = getKeyFromNode(n); CreateDependencyPropertyObject(((XamlElementStartNode)n).ElementType, ((XamlElementStartNode)n).name, key); } else if (n is XamlElementStartNode) { Debug.WriteLine(this.GetType() + ": element begins"); string key = getKeyFromNode(n); CreateObject(((XamlElementStartNode)n).ElementType, ((XamlElementStartNode)n).name, key); } else if (n is XamlPropertyNode && ((XamlPropertyNode)n).PropInfo != null) { Debug.WriteLine(this.GetType() + ": normal property begins"); CreateProperty(((XamlPropertyNode)n).PropInfo); } else if (n is XamlPropertyNode && ((XamlPropertyNode)n).DP != null) { Debug.WriteLine(this.GetType() + ": dependency property begins"); DependencyProperty dp = ((XamlPropertyNode)n).DP; Type typeAttachedTo = dp.OwnerType; string propertyName = ((XamlPropertyNode)n).PropertyName; CreateDependencyProperty(typeAttachedTo, propertyName, dp.PropertyType); } else if (n is XamlClrEventNode && !(((XamlClrEventNode)n).EventMember is EventInfo)) { Debug.WriteLine(this.GetType() + ": delegate property"); CreatePropertyDelegate(((XamlClrEventNode)n).Value, ((PropertyInfo)((XamlClrEventNode)n).EventMember).PropertyType); EndProperty(); } else if (n is XamlClrEventNode) { Debug.WriteLine(this.GetType() + ": event"); CreateEvent((EventInfo)((XamlClrEventNode)n).EventMember); CreateEventDelegate(((XamlClrEventNode)n).Value, ((EventInfo)((XamlClrEventNode)n).EventMember).EventHandlerType); EndEvent(); } else if (n is XamlTextNode && ((XamlTextNode)n).mode == XamlParseMode.Object){ Debug.WriteLine(this.GetType() + ": text for object"); CreateObjectText(((XamlTextNode)n).TextContent); } else if (n is XamlTextNode && ((XamlTextNode)n).mode == XamlParseMode.Property){ Debug.WriteLine(this.GetType() + ": text for property"); if (((XamlTextNode)n).keyText != null) CreatePropertyReference(((XamlTextNode)n).keyText); else CreatePropertyText(((XamlTextNode)n).TextContent, ((XamlTextNode)n).finalType); EndProperty(); } else if (n is XamlTextNode && ((XamlTextNode)n).mode == XamlParseMode.DependencyProperty){ Debug.WriteLine(this.GetType() + ": text for dependency property"); if (((XamlTextNode)n).keyText != null) CreateDependencyPropertyReference(((XamlTextNode)n).keyText); else CreateDependencyPropertyText(((XamlTextNode)n).TextContent, ((XamlTextNode)n).finalType); EndDependencyProperty(); } else if (n is XamlPropertyComplexEndNode) { Debug.WriteLine(this.GetType() + ": end complex property"); if (justClosed == 2) { EndProperty(); } else if (justClosed == 1) { EndDependencyProperty(); } else { throw new NotImplementedException("justClosed of " + justClosed); } justClosed = 0; } else if (n is XamlLiteralContentNode) { Debug.WriteLine(this.GetType() + ": literal content"); CreateCode(((XamlLiteralContentNode)n).Content); } else if (n is XamlElementEndNode) { Debug.WriteLine(this.GetType() + ": end element"); Type ft = ((XamlElementEndNode)n).finalType; if (((XamlElementEndNode)n).propertyObject) { EndPropertyObject(ft); justClosed = 2; } else if (((XamlElementEndNode)n).depPropertyObject) { EndDependencyPropertyObject(ft); justClosed = 1; } else { EndObject(); } } else if (n is XamlDocumentEndNode) { Debug.WriteLine(this.GetType() + ": end document"); Finish(); } else { throw new Exception("Unknown node " + n.GetType()); } } }
public XamlElement (XamlParser parser, string name) { Parser = parser; Name = name; }
public static void LoadComponent(object target, string resourceUri) { XamlLoader.Load(target, XamlParser.Parse(Granular.Compatibility.String.FromByteArray(EmbeddedResourceLoader.LoadResourceData(resourceUri)))); }
public XamlTypeConverter (XamlParser parser, XamlObjectElement element, string propertyName, Type destinationType) : base (propertyName, destinationType) { this.parser = parser; this.element = element; }
private static object ResolveResourceElement(Uri resourceUri) { string resourceString = Granular.Compatibility.String.FromByteArray(resourceDataCache.GetValue(resourceUri)); return(XamlLoader.Load(XamlParser.Parse(resourceString, resourceUri))); }
public static Value CreateFromFile (string file, bool create_namescope, bool validate_templates) { XamlParser p = new XamlParser () { CreateNameScope = create_namescope, ValidateTemplates = validate_templates, }; object v = p.ParseFile (file); return ObjectToValue (v); }
/// <summary> /// Initializes a new <see cref="XamlParserContext"/> /// </summary> /// <param name="handler">The <see cref="XamlParser"/> associated with the <see cref="XamlParserContext"/></param> public XamlParserContext(XamlParser handler) { this.Handler = handler; }
private static unsafe IntPtr ParseTemplate (Value *context_ptr, IntPtr resource_base, IntPtr surface, IntPtr binding_source, string xaml, ref MoonError error) { XamlContext context = Value.ToObject (typeof (XamlContext), context_ptr) as XamlContext; var parser = new XamlParser (context) { ResourceBase = UriHelper.FromNativeUri (resource_base), }; FrameworkElement fwe = null; var source = NativeDependencyObjectHelper.FromIntPtr (binding_source); if (source != null) { fwe = source as FrameworkElement; if (fwe == null) { error = new MoonError (parser.ParseException ("Only FrameworkElements can be used as TemplateBinding sources.")); return IntPtr.Zero; } } Log ("222222 ParseTemplateElement {0}", source); Log ("{0}", xaml); context.IsExpandingTemplate = true; context.TemplateOwner = source as DependencyObject; context.TemplateBindingSource = fwe; parser.HydrateObject = context.Template; INativeEventObjectWrapper dob = null; try { FrameworkTemplate template = parser.Parse (context.Node) as FrameworkTemplate; if (template != null) { dob = template.Content as INativeEventObjectWrapper; template.Content = null; } // No errors, but the template was just empty. if (dob == null) return IntPtr.Zero; } catch (Exception e) { error = new MoonError (e); return IntPtr.Zero; } finally { context.IsExpandingTemplate = false; context.TemplateOwner = null; context.TemplateBindingSource = null; } // XamlParser needs to ref its return value otherwise we can end up returning a an object to native // code with a refcount of '1' and it could then get GC'ed before we use it. Mono.NativeMethods.event_object_ref (dob.NativeHandle); return dob.NativeHandle; }
/// <summary> /// Creates a new XamlDesignContext instance. /// </summary> public XamlDesignContext(XmlReader xamlReader, XamlLoadSettings loadSettings) { if (xamlReader == null) { throw new ArgumentNullException("xamlReader"); } if (loadSettings == null) { throw new ArgumentNullException("loadSettings"); } this.Services.AddService(typeof(ISelectionService), new DefaultSelectionService()); this.Services.AddService(typeof(IComponentPropertyService), new ComponentPropertyService()); this.Services.AddService(typeof(IToolService), new DefaultToolService(this)); this.Services.AddService(typeof(UndoService), new UndoService()); this.Services.AddService(typeof(IErrorService), new DefaultErrorService(this)); this.Services.AddService(typeof(IOutlineNodeNameService), new OutlineNodeNameService()); this.Services.AddService(typeof(ViewService), new DefaultViewService(this)); this.Services.AddService(typeof(OptionService), new OptionService()); var xamlErrorService = new XamlErrorService(); this.Services.AddService(typeof(XamlErrorService), xamlErrorService); this.Services.AddService(typeof(IXamlErrorSink), xamlErrorService); _componentService = new XamlComponentService(this); this.Services.AddService(typeof(IComponentService), _componentService); foreach (Action <XamlDesignContext> action in loadSettings.CustomServiceRegisterFunctions) { action(this); } // register default versions of overridable services: if (this.Services.GetService(typeof(ITopLevelWindowService)) == null) { this.Services.AddService(typeof(ITopLevelWindowService), new WpfTopLevelWindowService()); } EditorManager.SetDefaultTextBoxEditorType(typeof(TextBoxEditor)); EditorManager.SetDefaultComboBoxEditorType(typeof(ComboBoxEditor)); // register extensions from the designer assemblies: foreach (Assembly designerAssembly in loadSettings.DesignerAssemblies) { this.Services.ExtensionManager.RegisterAssembly(designerAssembly); EditorManager.RegisterAssembly(designerAssembly); } _parserSettings = new XamlParserSettings(); _parserSettings.TypeFinder = loadSettings.TypeFinder; _parserSettings.CreateInstanceCallback = this.Services.ExtensionManager.CreateInstanceWithCustomInstanceFactory; _parserSettings.ServiceProvider = this.Services; _doc = XamlParser.Parse(xamlReader, _parserSettings); loadSettings.ReportErrors(xamlErrorService); if (_doc == null) { string message; if (xamlErrorService != null && xamlErrorService.Errors.Count > 0) { message = xamlErrorService.Errors[0].Message; } else { message = "Could not load document."; } throw new XamlLoadException(message); } _rootItem = _componentService.RegisterXamlComponentRecursive(_doc.RootElement); if (_rootItem != null) { var rootBehavior = new RootItemBehavior(); rootBehavior.Intialize(this); } _xamlEditOperations = new XamlEditOperations(this, _parserSettings); }
public SL4MarkupExpressionParser (object target, string attribute_name, XamlParser parser, XamlObjectElement target_element) : base (target, attribute_name) { this.parser = parser; this.target_element = target_element; }
private static void Main(string[] args) { // Control window = ConsoleApplication.LoadFromXaml( "ConsoleFramework.Layout.xml", null ); //// window.FindChildByName< TextBlock >( "text" ).MouseDown += ( sender, eventArgs ) => { //// window.FindChildByName< TextBlock >( "text" ).Text = "F"; //// eventArgs.Handled = true; //// }; //// window.MouseDown += ( sender, eventArgs ) => { //// window.Width = window.ActualWidth + 3; //// window.Invalidate( ); //// }; // ConsoleApplication.Instance.Run( window ); // return; var assembly = Assembly.GetExecutingAssembly(); var resourceName = "Examples.GridTest.xml"; Window createdFromXaml; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); MyDataContext dataContext = new MyDataContext( ); dataContext.Str = "Введите заголовок"; createdFromXaml = XamlParser.CreateFromXaml <Window>(result, dataContext, new List <string>() { "clr-namespace:Xaml;assembly=Xaml", "clr-namespace:ConsoleFramework.Xaml;assembly=ConsoleFramework", "clr-namespace:ConsoleFramework.Controls;assembly=ConsoleFramework", }); } // ConsoleApplication.Instance.Run(createdFromXaml); // return; using (ConsoleApplication application = ConsoleApplication.Instance) { Panel panel = new Panel(); panel.Name = "panel1"; panel.HorizontalAlignment = HorizontalAlignment.Center; panel.VerticalAlignment = VerticalAlignment.Stretch; panel.XChildren.Add(new TextBlock() { Name = "label1", Text = "Label1", Margin = new Thickness(1, 2, 1, 0) //,Visibility = Visibility.Collapsed }); panel.XChildren.Add(new TextBlock() { Name = "label2", Text = "Label2_____", HorizontalAlignment = HorizontalAlignment.Right }); TextBox textBox = new TextBox() { MaxWidth = 10, Margin = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center, Size = 15 }; Button button = new Button() { Name = "button1", Caption = "Button!", Margin = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center }; button.OnClick += (sender, eventArgs) => { Debug.WriteLine("Click"); MessageBox.Show("Окно сообщения", "Внимание ! Тестовое сообщение", delegate(MessageBoxResult result) { }); Control label = panel.FindDirectChildByName("label1"); if (label.Visibility == Visibility.Visible) { label.Visibility = Visibility.Collapsed; } else if (label.Visibility == Visibility.Collapsed) { label.Visibility = Visibility.Hidden; } else { label.Visibility = Visibility.Visible; } label.Invalidate(); }; ComboBox comboBox = new ComboBox( ) { // Width = 14 //HorizontalAlignment = HorizontalAlignment.Stretch }; comboBox.Items.Add("Сделать одно"); comboBox.Items.Add("Сделать второе"); comboBox.Items.Add("Ничего не делать"); ListBox listbox = new ListBox( ); listbox.Items.Add("First item"); listbox.Items.Add("second item1!!!!!!1fff"); listbox.HorizontalAlignment = HorizontalAlignment.Stretch; //listbox.Width = 10; panel.XChildren.Add(comboBox); panel.XChildren.Add(button); panel.XChildren.Add(textBox); panel.XChildren.Add(listbox); //application.Run(panel); WindowsHost windowsHost = new WindowsHost() { Name = "WindowsHost" }; Window window1 = new Window { X = 5, Y = 4, //MinHeight = 100, //MaxWidth = 30, //Width = 10, Height = 20, Name = "Window1", Title = "Window1", Content = panel }; GroupBox groupBox = new GroupBox( ); groupBox.Title = "Группа"; ScrollViewer scrollViewer = new ScrollViewer( ); ListBox listBox = new ListBox( ); for (int i = 0; i < 30; i++) { listBox.Items.Add(string.Format("Длинный элемент {0}", i)); } // listBox.Items.Add( "Длинный элемент" ); // listBox.Items.Add("Длинный элемент 2"); // listBox.Items.Add("Длинный элемент 3"); // listBox.Items.Add("Длинный элемент 4"); // listBox.Items.Add("Длинный элемент 5"); // listBox.Items.Add("Длинный элемент 6"); // listBox.Items.Add("Длинный элемент 700"); listBox.HorizontalAlignment = HorizontalAlignment.Stretch; listBox.VerticalAlignment = VerticalAlignment.Stretch; scrollViewer.Content = listBox; // scrollViewer.HorizontalAlignment = HorizontalAlignment.Stretch; scrollViewer.VerticalAlignment = VerticalAlignment.Stretch; scrollViewer.HorizontalScrollEnabled = true; groupBox.Content = scrollViewer; ComboBox combo = new ComboBox(); combo.ShownItemsCount = 10; for (int i = 0; i < 30; i++) { combo.Items.Add(string.Format("Длинный элемент {0}", i)); } // groupBox.Content = combo; groupBox.HorizontalAlignment = HorizontalAlignment.Stretch; windowsHost.Show(new Window() { X = 30, Y = 6, //MinHeight = 10, //MinWidth = 10, Height = 14, Name = "LongTitleWindow", Title = "Очень длинное название окна", Content = groupBox }); windowsHost.Show(window1); windowsHost.Show(createdFromXaml); //textBox.SetFocus(); todo : научиться задавать фокусный элемент до добавления в визуальное дерево //application.TerminalSizeChanged += ( sender, eventArgs ) => { // application.CanvasSize = new Size(eventArgs.Width, eventArgs.Height); // application.RootElementRect = new Rect(new Size(eventArgs.Width, eventArgs.Height)); // }; //windowsHost.Width = 80; //windowsHost.Height = 20; application.Run(windowsHost); //, new Size(80, 30), Rect.Empty); } }
/// <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) { 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.document = root.OwnerDocument; var xamlObject = parser.ParseObject(element as XmlElement); if (xamlObject != null) return xamlObject; } return null; }
public SL4MarkupExpressionParser(object target, string attribute_name, XamlParser parser, XamlObjectElement target_element) : base(target, attribute_name) { this.parser = parser; this.target_element = target_element; }
/// <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; }
/// <summary> /// Paste items from clipboard into the designer. /// </summary> public void Paste() { bool pasted = false; string combinedXaml = Clipboard.GetText(TextDataFormat.Xaml); IEnumerable <string> xamls = combinedXaml.Split(_delimeter); xamls = xamls.Where(xaml => xaml != ""); DesignItem parent = _context.Services.Selection.PrimarySelection; DesignItem child = _context.Services.Selection.PrimarySelection; XamlDesignItem rootItem = _context.RootItem as XamlDesignItem; var pastedItems = new Collection <DesignItem>(); foreach (var xaml in xamls) { var obj = XamlParser.ParseSnippet(rootItem.XamlObject, xaml, _settings); if (obj != null) { DesignItem item = _context._componentService.RegisterXamlComponentRecursive(obj); if (item != null) { pastedItems.Add(item); } } } if (pastedItems.Count != 0) { var changeGroup = _context.OpenGroup("Paste " + pastedItems.Count + " elements", pastedItems); while (parent != null && pasted == false) { if (parent.ContentProperty != null) { if (parent.ContentProperty.IsCollection) { if (CollectionSupport.CanCollectionAdd(parent.ContentProperty.ReturnType, pastedItems.Select(item => item.Component)) && parent.GetBehavior <IPlacementBehavior>() != null) { AddInParent(parent, pastedItems); pasted = true; } } else if (pastedItems.Count == 1 && parent.ContentProperty.Value == null && parent.ContentProperty.ValueOnInstance == null && parent.View is ContentControl) { AddInParent(parent, pastedItems); pasted = true; } if (!pasted) { parent = parent.Parent; } } else { parent = parent.Parent; } } while (pasted == false) { if (child.ContentProperty != null) { if (child.ContentProperty.IsCollection) { foreach (var col in child.ContentProperty.CollectionElements) { if (col.ContentProperty != null && col.ContentProperty.IsCollection) { if (CollectionSupport.CanCollectionAdd(col.ContentProperty.ReturnType, pastedItems.Select(item => item.Component))) { pasted = true; } } } break; } else if (child.ContentProperty.Value != null) { child = child.ContentProperty.Value; } else if (pastedItems.Count == 1) { child.ContentProperty.SetValue(pastedItems.First().Component); pasted = true; break; } else { break; } } else { break; } } foreach (var pastedItem in pastedItems) { _context._componentService.RaiseComponentRegisteredAndAddedToContainer(pastedItem); } changeGroup.Commit(); } }
private static unsafe IntPtr ParseTemplate (Value *context_ptr, string resource_base, IntPtr surface, IntPtr binding_source, string xaml, ref MoonError error) { XamlContext context = Value.ToObject (typeof (XamlContext), context_ptr) as XamlContext; var parser = new XamlParser (context); var source = NativeDependencyObjectHelper.FromIntPtr (binding_source); if (source == null) { error = new MoonError (parser.ParseException ("Attempting to parse a template with an invalid binding source.")); return IntPtr.Zero; } FrameworkElement fwe = source as FrameworkElement; if (fwe == null) { error = new MoonError (parser.ParseException ("Only FrameworkElements can be used as TemplateBinding sources.")); return IntPtr.Zero; } context.IsExpandingTemplate = true; context.TemplateBindingSource = fwe; INativeEventObjectWrapper dob = null; try { dob = parser.ParseString (xaml) as INativeEventObjectWrapper; } catch (Exception e) { error = new MoonError (e); return IntPtr.Zero; } if (dob == null) { error = new MoonError (parser.ParseException ("Unable to parse template item.")); return IntPtr.Zero; } return dob.NativeHandle; }
public void ItemsControlTemplatesTest() { string text = @" <ItemsControl xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <DockPanel/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.Template> <ControlTemplate> <Grid> <TextBlock Text='Header'/> <ItemsPresenter ItemContainerGenerator='{TemplateBinding ItemsControl.ItemContainerGenerator}' Template='{TemplateBinding ItemsControl.ItemsPanel}'/> </Grid> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemContainerStyle> <Style> <Setter Property='DockPanel.Dock' Value='Bottom'/> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text='{Binding}'/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>"; ItemsControl itemsControl = XamlLoader.Load(XamlParser.Parse(text)) as ItemsControl; itemsControl.Items.Add("item1"); itemsControl.Items.Add("item2"); itemsControl.Items.Add("item3"); Grid grid = itemsControl.VisualChildren.FirstOrDefault() as Grid; Assert.IsNotNull(grid); Assert.AreEqual(2, grid.Children.Count); TextBlock textBlock = grid.Children[0] as TextBlock; ItemsPresenter itemsPresenter = grid.Children[1] as ItemsPresenter; Assert.IsNotNull(textBlock); Assert.IsNotNull(itemsPresenter); Assert.AreEqual("Header", textBlock.Text); DockPanel dockPanel = itemsPresenter.VisualChildren.FirstOrDefault() as DockPanel; Assert.IsNotNull(dockPanel); Assert.AreEqual(3, dockPanel.Children.Count); ContentPresenter presenter1 = dockPanel.Children[0] as ContentPresenter; ContentPresenter presenter2 = dockPanel.Children[1] as ContentPresenter; ContentPresenter presenter3 = dockPanel.Children[2] as ContentPresenter; Assert.IsNotNull(presenter1); Assert.IsNotNull(presenter2); Assert.IsNotNull(presenter3); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter1)); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter2)); Assert.AreEqual(Dock.Bottom, DockPanel.GetDock(presenter3)); TextBlock textBlock1 = presenter1.VisualChildren.FirstOrDefault() as TextBlock; Assert.IsNotNull(textBlock1); Assert.AreEqual("item1", textBlock1.Text); itemsControl.Items[0] = "item4"; Assert.IsFalse(presenter1.VisualChildren.Any()); Assert.IsNull(textBlock1.Text); ContentPresenter presenter4 = dockPanel.Children[0] as ContentPresenter; Assert.AreNotEqual(presenter1, presenter4); TextBlock textBlock4 = presenter4.VisualChildren.FirstOrDefault() as TextBlock; Assert.AreEqual("item4", textBlock4.Text); }