/// <summary> /// Adds an item to the current XML tree, underneath the currently selected node. /// <para>DEVNOTE: This method makes many presumptions upon the Views' structure and format. /// As such any changes to the View will likely break this method.</para> /// </summary> /// <param name="parameter"></param> internal void AddItem(object parameter) { // Parameter should be the button that launched the command. var btn = parameter as Button; // Check we have both a button and a node to use. if (btn == null || SelectedNode == null) { return; } // As such it's parent should be a stackpanel. var parent = LogicalTreeHelper.GetParent(btn) as StackPanel; if (parent != null) { // There should only be 1 textbox control. var textBox = parent.Children.OfType <TextBox>().First(); // If no text, exit here. We cannot create an element with no name. if (string.IsNullOrEmpty(textBox?.Text)) { return; } // Name of control should contain type of item to add. ProjectItemType itemType; if (textBox.Name.ToLower().Contains(Strings.FOLDER_TAG)) { itemType = ProjectItemType.Folder; } else if (textBox.Name.ToLower().Contains(Strings.FILE_TAG)) { itemType = ProjectItemType.File; } else { return; // We should show an error here? } // Create new node. var newNode = SelectedNode.OwnerDocument.CreateNode(XmlNodeType.Element, itemType.ToString().ToLower(), SelectedNode.NamespaceURI); // Set node name. ((XmlElement)newNode).SetAttribute(Strings.Attributes[XmlAttributeName.Name], textBox.Text); // Append new node to selected node. SelectedNode.AppendChild(newNode); // Save XML file. SelectedNode.OwnerDocument.Save(CurrentDataFile); // Reload XML file. (Seems to help prevent errors) LoadXml(CurrentDataFile); // Select the new node for editing. SelectedNode = newNode; // Clear text box for next input. textBox.Text = ""; } // Close context menu var upLevel = LogicalTreeHelper.GetParent(parent); ContextMenu menu = upLevel as ContextMenu; while (menu == null && upLevel != null) { upLevel = LogicalTreeHelper.GetParent(upLevel); menu = upLevel as ContextMenu; } if (menu != null) { menu.IsOpen = false; } }