private Connector GetConnector(Guid itemID, String connectorName)
        {
            DesignerItem designerItem = (from item in this.Children.OfType <DesignerItem>()
                                         where item.ID == itemID
                                         select item).FirstOrDefault();

            Control connectorDecorator = designerItem.Template.FindName("PART_ConnectorDecorator", designerItem) as Control;

            connectorDecorator.ApplyTemplate();

            return(connectorDecorator.Template.FindName(connectorName, connectorDecorator) as Connector);
        }
 private void SetConnectorDecoratorTemplate(DesignerItem item)
 {
     if (item.ApplyTemplate() && item.Content is UIElement)
     {
         ControlTemplate template  = DesignerItem.GetConnectorDecoratorTemplate(item.Content as UIElement);
         Control         decorator = item.Template.FindName("PART_ConnectorDecorator", item) as Control;
         if (decorator != null && template != null)
         {
             decorator.Template = template;
         }
     }
 }
        public void RemoveRecursivelyConnectedItem(Connection connection)
        {
            Connector    source_connector = connection.Source;
            Connector    sink_connector   = connection.Sink;
            DesignerItem designerItem     = sink_connector.ParentDesignerItem;
            Connector    left_connector   = designerItem.GetConnector("Left");
            Connector    right_connector  = designerItem.GetConnector("Right");
            Connector    bottom_connector = designerItem.GetConnector("Bottom");

            List <Connection> connections = left_connector.Connections;

            connections.ForEach(delegate(Connection tmp_connection)
            {
                if (tmp_connection.Source == left_connector)
                {
                    RemoveRecursivelyConnectedItem(tmp_connection);
                }
                else
                {
                    this.Children.Remove(tmp_connection);
                }
            });
            connections = right_connector.Connections;
            connections.ForEach(delegate(Connection tmp_connection)
            {
                if (tmp_connection.Source == right_connector)
                {
                    RemoveRecursivelyConnectedItem(tmp_connection);
                }
                else
                {
                    this.Children.Remove(tmp_connection);
                }
            });
            connections = bottom_connector.Connections;
            connections.ForEach(delegate(Connection tmp_connection)
            {
                if (tmp_connection.Source == bottom_connector)
                {
                    RemoveRecursivelyConnectedItem(tmp_connection);
                }
                else
                {
                    this.Children.Remove(tmp_connection);
                }
            });

            this.Children.Remove(connection);
            this.Children.Remove(designerItem);
            //while()
        }
        private static DesignerItem DeserializeDesignerItem(XElement itemXML, Guid id, double OffsetX, double OffsetY)
        {
            DesignerItem item = new DesignerItem(id);

            item.Width    = Double.Parse(itemXML.Element("Width").Value, CultureInfo.InvariantCulture);
            item.Height   = Double.Parse(itemXML.Element("Height").Value, CultureInfo.InvariantCulture);
            item.ParentID = new Guid(itemXML.Element("ParentID").Value);
            item.IsGroup  = Boolean.Parse(itemXML.Element("IsGroup").Value);
            Canvas.SetLeft(item, Double.Parse(itemXML.Element("Left").Value, CultureInfo.InvariantCulture) + OffsetX);
            Canvas.SetTop(item, Double.Parse(itemXML.Element("Top").Value, CultureInfo.InvariantCulture) + OffsetY);
            Canvas.SetZIndex(item, Int32.Parse(itemXML.Element("zIndex").Value));
            Object content = XamlReader.Load(XmlReader.Create(new StringReader(itemXML.Element("Content").Value)));

            item.Content = content;
            return(item);
        }
        private void CopyCurrentSelection()
        {
            IEnumerable <DesignerItem> selectedDesignerItems =
                this.SelectionService.CurrentSelection.OfType <DesignerItem>();

            List <Connection> selectedConnections =
                this.SelectionService.CurrentSelection.OfType <Connection>().ToList();

            foreach (Connection connection in this.Children.OfType <Connection>())
            {
                if (!selectedConnections.Contains(connection))
                {
                    DesignerItem sourceItem = (from item in selectedDesignerItems
                                               where item.ID == connection.Source.ParentDesignerItem.ID
                                               select item).FirstOrDefault();

                    DesignerItem sinkItem = (from item in selectedDesignerItems
                                             where item.ID == connection.Sink.ParentDesignerItem.ID
                                             select item).FirstOrDefault();

                    if (sourceItem != null &&
                        sinkItem != null &&
                        BelongToSameGroup(sourceItem, sinkItem))
                    {
                        selectedConnections.Add(connection);
                    }
                }
            }

            XElement designerItemsXML = SerializeDesignerItems(selectedDesignerItems);
            XElement connectionsXML   = SerializeConnections(selectedConnections);

            XElement root = new XElement("Root");

            root.Add(designerItemsXML);
            root.Add(connectionsXML);

            root.Add(new XAttribute("OffsetX", 10));
            root.Add(new XAttribute("OffsetY", 10));

            Clipboard.Clear();
            Clipboard.SetData(DataFormats.Xaml, root);
        }
        private void Open_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            XElement root = LoadSerializedDataFromFile();

            if (root == null)
            {
                return;
            }

            this.Children.Clear();
            this.SelectionService.ClearSelection();

            IEnumerable <XElement> itemsXML = root.Elements("DesignerItems").Elements("DesignerItem");

            foreach (XElement itemXML in itemsXML)
            {
                Guid         id   = new Guid(itemXML.Element("ID").Value);
                DesignerItem item = DeserializeDesignerItem(itemXML, id, 0, 0);
                this.Children.Add(item);
                SetConnectorDecoratorTemplate(item);
            }

            this.InvalidateVisual();

            IEnumerable <XElement> connectionsXML = root.Elements("Connections").Elements("Connection");

            foreach (XElement connectionXML in connectionsXML)
            {
                Guid sourceID = new Guid(connectionXML.Element("SourceID").Value);
                Guid sinkID   = new Guid(connectionXML.Element("SinkID").Value);

                String sourceConnectorName = connectionXML.Element("SourceConnectorName").Value;
                String sinkConnectorName   = connectionXML.Element("SinkConnectorName").Value;

                Connector sourceConnector = GetConnector(sourceID, sourceConnectorName);
                Connector sinkConnector   = GetConnector(sinkID, sinkConnectorName);

                Connection connection = new Connection(sourceConnector, sinkConnector);
                Canvas.SetZIndex(connection, Int32.Parse(connectionXML.Element("zIndex").Value));
                this.Children.Add(connection);
            }
        }
        private void Paste_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            XElement root = LoadSerializedDataFromClipBoard();

            if (root == null)
            {
                return;
            }

            // create DesignerItems
            Dictionary <Guid, Guid> mappingOldToNewIDs = new Dictionary <Guid, Guid>();
            List <ISelectable>      newItems           = new List <ISelectable>();
            IEnumerable <XElement>  itemsXML           = root.Elements("DesignerItems").Elements("DesignerItem");

            double offsetX = Double.Parse(root.Attribute("OffsetX").Value, CultureInfo.InvariantCulture);
            double offsetY = Double.Parse(root.Attribute("OffsetY").Value, CultureInfo.InvariantCulture);

            foreach (XElement itemXML in itemsXML)
            {
                Guid oldID = new Guid(itemXML.Element("ID").Value);
                Guid newID = Guid.NewGuid();
                mappingOldToNewIDs.Add(oldID, newID);
                DesignerItem item = DeserializeDesignerItem(itemXML, newID, offsetX, offsetY);
                this.Children.Add(item);
                SetConnectorDecoratorTemplate(item);
                newItems.Add(item);
            }

            // update group hierarchy
            SelectionService.ClearSelection();
            foreach (DesignerItem el in newItems)
            {
                if (el.ParentID != Guid.Empty)
                {
                    el.ParentID = mappingOldToNewIDs[el.ParentID];
                }
            }


            foreach (DesignerItem item in newItems)
            {
                if (item.ParentID == Guid.Empty)
                {
                    SelectionService.AddToSelection(item);
                }
            }

            // create Connections
            IEnumerable <XElement> connectionsXML = root.Elements("Connections").Elements("Connection");

            foreach (XElement connectionXML in connectionsXML)
            {
                Guid oldSourceID = new Guid(connectionXML.Element("SourceID").Value);
                Guid oldSinkID   = new Guid(connectionXML.Element("SinkID").Value);

                if (mappingOldToNewIDs.ContainsKey(oldSourceID) && mappingOldToNewIDs.ContainsKey(oldSinkID))
                {
                    Guid newSourceID = mappingOldToNewIDs[oldSourceID];
                    Guid newSinkID   = mappingOldToNewIDs[oldSinkID];

                    String sourceConnectorName = connectionXML.Element("SourceConnectorName").Value;
                    String sinkConnectorName   = connectionXML.Element("SinkConnectorName").Value;

                    Connector sourceConnector = GetConnector(newSourceID, sourceConnectorName);
                    Connector sinkConnector   = GetConnector(newSinkID, sinkConnectorName);

                    Connection connection = new Connection(sourceConnector, sinkConnector);
                    Canvas.SetZIndex(connection, Int32.Parse(connectionXML.Element("zIndex").Value));
                    this.Children.Add(connection);

                    SelectionService.AddToSelection(connection);
                }
            }

            DesignerCanvas.BringToFront.Execute(null, this);

            // update paste offset
            root.Attribute("OffsetX").Value = (offsetX + 10).ToString();
            root.Attribute("OffsetY").Value = (offsetY + 10).ToString();
            Clipboard.Clear();
            Clipboard.SetData(DataFormats.Xaml, root);
        }
        protected override void OnDrop(DragEventArgs e)
        {
            Custom_Functions.Validation_OnDrop validation = new Custom_Functions.Validation_OnDrop();

            bool check = validation.Validation_Check(e);

            if (check == false)
            {
                return;
            }
            else
            {
                base.OnDrop(e);
                DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject;
                if (dragObject != null && !String.IsNullOrEmpty(dragObject.Xaml))
                {
                    DesignerItem newItem = null;
                    Object       content = XamlReader.Load(XmlReader.Create(new StringReader(dragObject.Xaml)));

                    if (content != null)
                    {
                        newItem         = new DesignerItem();
                        newItem.Content = content;
                        newItem.Init();

                        Point position = e.GetPosition(this);

                        if (dragObject.DesiredSize.HasValue)
                        {
                            Size desiredSize = dragObject.DesiredSize.Value;
                            newItem.Width  = desiredSize.Width;
                            newItem.Height = desiredSize.Height;

                            DesignerCanvas.SetLeft(newItem, Math.Max(0, position.X - newItem.Width / 2));
                            DesignerCanvas.SetTop(newItem, Math.Max(0, position.Y - newItem.Height / 2));
                        }
                        else
                        {
                            DesignerCanvas.SetLeft(newItem, Math.Max(0, position.X));
                            DesignerCanvas.SetTop(newItem, Math.Max(0, position.Y));
                        }

                        Canvas.SetZIndex(newItem, this.Children.Count);
                        this.Children.Add(newItem);
                        SetConnectorDecoratorTemplate(newItem);

                        //update selection
                        this.SelectionService.SelectItem(newItem);
                        newItem.Focus();

                        var timer = new System.Windows.Threading.DispatcherTimer {
                            Interval = TimeSpan.FromSeconds(0.5)
                        };
                        timer.Start();
                        timer.Tick += (sender, args) =>
                        {
                            timer.Stop();
                            this.connectAutomatically();
                        };
                    }

                    e.Handled = true;
                }
            }
        }
        private void connectAutomatically()
        {
            UIElementCollection myUIElementCollection = this.Children;
            DesignerItem        source = null, sink = null;

            foreach (UIElement childElement in myUIElementCollection)
            {
                DesignerItem designerItem = childElement as DesignerItem;
                if (designerItem != null)
                {
                    if (source == null)
                    {
                        if (designerItem.IsAvailableForConnect())
                        {
                            source = designerItem;
                        }
                    }
                    else
                    {
                        if (designerItem.Current_Sink_Connection_Cnt == 0)
                        {
                            sink = designerItem;
                            break;
                        }
                    }
                }
            }
            if (source != null && sink != null)
            {
                var temp_grid                  = System.Windows.Media.VisualTreeHelper.GetChild(source, 0);
                var part_connector             = System.Windows.LogicalTreeHelper.FindLogicalNode(temp_grid, "PART_ConnectorDecorator");
                var source_part_connector_grid = System.Windows.Media.VisualTreeHelper.GetChild(part_connector, 0);

                temp_grid      = System.Windows.Media.VisualTreeHelper.GetChild(sink, 0);
                part_connector = System.Windows.LogicalTreeHelper.FindLogicalNode(temp_grid, "PART_ConnectorDecorator");
                var        sink_part_connector_grid = System.Windows.Media.VisualTreeHelper.GetChild(part_connector, 0);
                Connector  sink_top_connector       = System.Windows.LogicalTreeHelper.FindLogicalNode(sink_part_connector_grid, "Top") as Connector;
                Connection newConnection            = null;
                switch (source.Current_Connection_Cnt)
                {
                case 0:
                    Connector botom_connector = System.Windows.LogicalTreeHelper.FindLogicalNode(source_part_connector_grid, "Bottom") as Connector;
                    newConnection = new Connection(botom_connector, sink_top_connector);
                    break;

                case 1:
                    botom_connector = System.Windows.LogicalTreeHelper.FindLogicalNode(source_part_connector_grid, "Bottom") as Connector;
                    Connector left_connector  = System.Windows.LogicalTreeHelper.FindLogicalNode(source_part_connector_grid, "Left") as Connector;
                    Connector right_connector = System.Windows.LogicalTreeHelper.FindLogicalNode(source_part_connector_grid, "Right") as Connector;
                    if (botom_connector.Connections.Capacity >= 1)
                    {
                        botom_connector.Connections.ForEach(delegate(Connection connection)
                        {
                            if (connection.Source == botom_connector)
                            {
                                connection.Source = left_connector;
                            }
                        });
                    }
                    if (source.Max_Connection_Cnt == 2)
                    {
                        newConnection = new Connection(right_connector, sink_top_connector);
                    }
                    else
                    {
                        newConnection = new Connection(botom_connector, sink_top_connector);
                    }
                    break;

                case 2:
                    right_connector = System.Windows.LogicalTreeHelper.FindLogicalNode(source_part_connector_grid, "Right") as Connector;
                    newConnection   = new Connection(right_connector, sink_top_connector);
                    break;
                }
                if (newConnection != null)
                {
                    Canvas.SetZIndex(newConnection, this.Children.Count);
                    this.Children.Add(newConnection);
                }
            }
        }