Click here to Skip to main content
15,891,905 members
Articles / Desktop Programming / Windows Forms
Article

Drawing Windows Controls During Runtime Based on XML Feed

Rate me:
Please Sign up or sign in to vote.
4.43/5 (3 votes)
1 Aug 2011CPOL2 min read 21.7K   690   20   4
How to draw Windows Controls during runtime based on XML feed

Introduction

We design Windows native application by dragging and dropping components on the form directly using an IDE like Visual Studio. Nothing new – every Windows developer is familiar. It enables rapid application development and gives us more time to concentrate on implementing business rules efficiently that drives the whole system. All is good and fine so far. In other times, we might have to add these very widgets during runtime. One of the reasons might be that we want our system as flexible as possible. Drawing these components during runtime is fun and equally challenging. This article focuses on designing a simple GUI where the form components are added dynamically rather than during design time.

XML Feed

For this application, we will use XML document to describe its content and content–type. This allows us to launch different applications from a single form. One of the examples can be installation application that you might want to create in future. XPath is used to traverse through it. XML document looks like this:

XML
<?xml version="1.0"?>
<MenuItem BasePath="c:\SampleApplication">
  <SideMenuItem Title="Documents">
    <Item ID="Document"
          LinkText="PDF Document"
          DetailText="View my pdf document"
          LinkType="pdf"
          Icon="\Icons\pdf.ico"
          ResourceLocation="\Resources\sampleDoc.pdf"
          />
   </SideMenuItem>
  <SideMenuItem Title="Softwares">
    <Item ID="CoolApp"
          LinkText="Next Cool Application"
          DetailText="Launch Cool Application"
          LinkType="exe"
          Icon="\Icons\exe.ico"
          ResourceLocation="="\Resources\CoolApp.exe"
          />
    <Item ID="KillerApp"
          LinkText="Next Killer application"
          DetailText="Launch Killer Application"
          LinkType="exe"
          Icon="\Icons\exe.ico"
          ResourceLocation="\Resources\KillerApp.exe "
          />
   </SideMenuItem>
  <SideMenuItem Title="Support">
    <Item ID="SupportSite"
          LinkText="Support Site"
          DetailText="Visit Support Site"
          LinkType="url"
           Icon="\Icons\ie.ico"
          ResourceLocation="\Resources\support.htm"
          />
  </SideMenuItem>
</MenuItem>

The above XML document describes two categories – Document and Software. Within each category, it has two items each. Category or “MainLink” tag makes side menu item and “Item” tag describes content and content link for our Windows Form. XPath traverses each node and retrieves necessary values.

Parsing XML Document

XmlDocument class is used to load XML feed.

C#
XmlDocument  xDoc = new XmlDocument();

Once loaded in xDoc object, the following XPath expression retrieves all “MainLink” items.

Get all “<MainLink>”:

C#
XmlNodeList nodeSideMenuItems = doc.SelectNodes("MenuItem/SideMenuItem");

Then it carries on traversing items within.

C#
XmlNodeList nodes = sNode.SelectNodes("Item");

SideMenuItem is the class representing XML document. During XML parsing, all relevant node values are stored in List<SideMenuItem>. Class definition is shown below:

C#
public class SideMenuItem
    {
        public string TagName { get; set; }
        public List<ContentMenuItem> MenuItemList { get; set; }
    }

public class ContentMenuItem
    {
        public string TagName { get; set; }
        public string LinkText { get; set; }
        public string DetailText { get; set; }
        public string LinkType { get; set; }
        public string IconLocation { get; set; }
        public string ResourceLocation { get; set; }
    }

Controls at Runtime

We have done our homework by parsing Feed.xml document and populated List<SideMenuItem> lists. The fun part begins now. We will add the controls both to side and content panel and register required events. Main methods responsible are briefly explained.

  1. Code snippet for GenerateSidePanelControls() – Adds “Label” control to side panel of type “Panel” class and registers Click, Mouse Enter and Mouse Leave events.
    C#
    int topPosition = 15;
           foreach (SideMenuItem sItem in _sideMenuItemList)
            {
              Label objLabel = new Label();
              objLabel.Name = sItem.TagName;
              objLabel.Text = sItem.TagName;
              objLabel.Left = 15;
              objLabel.Top = topPosition;
              objLabel.Font = _normalFont;
              sidePanel.Controls.Add(objLabel);
              topPosition += 25;
    
              objLabel.Click += new System.EventHandler(SideLabel_Click);
                     objLabel.MouseEnter += 
    			new System.EventHandler(SideLabel_MouseEnter);
              objLabel.MouseLeave += new System.EventHandler(SideLabel_MouseLeave);
             }
  2. Code snippet for SideLabel_Click() – Adds main content controls when use clicks on the side menu items.
    C#
    Label objLabel = (Label)sender;
           objLabel.Font = _boldFont;
           //Make rest of the Side Label have normal font
           foreach (Control ctrl in sidePanel.Controls)
           	{
                   if (ctrl is Label)
                   {
                        if (ctrl.Name != objLabel.Name)
                         {
                           ctrl.Font = _normalFont;
                         }
                      }
                   }
                   GenerateContentPanelControls(objLabel.Name);
  3. Code snippet for GenerateContentPanelControls(string sTagName) – Adds main content controls when user clicks on side menu item based side menu item title or tag name.
    C#
    //Get the side menu item based on tagName
                    SideMenuItem sMenuItem = null;
                    foreach (SideMenuItem sItem in _sideMenuItemList)
                    {
                        if (sItem.TagName == sTagName)
                        {
                            sMenuItem = sItem;
                            break;
                        }
                    }
                    contentPanel.Controls.Clear();
    
                    Label spacer = new Label();
                    spacer.Height = 10;
                    spacer.Width = 562;
                    contentPanel.Controls.Add(spacer);
    
                    foreach (ContentMenuItem cItem in sMenuItem.MenuItemList)
                    {
                        FlowLayoutPanel flowLayoutPanel = new FlowLayoutPanel();
                        flowLayoutPanel.Width = 550;
                        flowLayoutPanel.AutoSize = true;
    
                        // <IconLocation> tag control
                        string iconLocation = cItem.IconLocation;
                        PictureBox icon = new PictureBox();
                        icon.Size = new Size(50, 50);
                        icon.Image = new Bitmap(iconLocation);
                        icon.SizeMode = PictureBoxSizeMode.CenterImage;
                        flowLayoutPanel.Controls.Add(icon);
    
                        // innerFlowPanel
                        FlowLayoutPanel innerFlowPanel = new FlowLayoutPanel();
                        innerFlowPanel.Width = 500;
    
                        // <LinkText> tag control
                        string linkText = cItem.LinkText;
                        Label lblLinkText = new Label();
                        lblLinkText.Name = cItem.TagName;
                        lblLinkText.Text = linkText;
                        lblLinkText.Font = _normalFont;
                        lblLinkText.ForeColor = Color.Blue;
                        lblLinkText.AutoSize = true;
                        innerFlowPanel.Controls.Add(lblLinkText);
    
                        // linebreak
                        Label lineBreak = new Label();
                        lineBreak.Height = 0;
                        lineBreak.Width = 562 - (lblLinkText.Width + icon.Width);
                        innerFlowPanel.Controls.Add(lineBreak);
    
                        // <DetailText>
                        string detailText = cItem.DetailText;
                        Label lblDetailText = new Label();
                        lblDetailText.Text = detailText;
                        lblDetailText.Font = _normalFont;
                        lblDetailText.AutoSize = true;
                        innerFlowPanel.Controls.Add(lblDetailText);
    
                        innerFlowPanel.Height = lblLinkText.DisplayRectangle.Height + 
                        	lblDetailText.DisplayRectangle.Height + 5;
    
                        flowLayoutPanel.Controls.Add(innerFlowPanel);
    
                        contentPanel.Controls.Add(flowLayoutPanel);
    
                        //Register events 
                        lblLinkText.Click += 
    			new System.EventHandler(ContentLabel_Click);
                        lblLinkText.MouseEnter += 
    			new System.EventHandler(ContentLabel_MouseEnter);
                        lblLinkText.MouseLeave += 
    			new System.EventHandler(ContentLabel_MouseLeave);
                    }

UI Look

As per the feed.xml, the following components are drawn on the form at run-time:

image001.gif

Conclusion

Adding controls at runtime provides a different benefit. We don’t have to design the form again and again when the content changes. We simply inject different XML feed.

Let’s share ideas.

History

  • 31st July, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
Milan has been developing commercial applications over a decade primarily on Windows platform. When not programming, he loves to test his physical endurance - running far away to unreachable distance or hiking up in the mountains to play with Yaks and wanting to teach 'Yeti' programming!

Comments and Discussions

 
SuggestionPut resource in same exe folder Pin
Hoangitk1-Aug-11 16:45
professionalHoangitk1-Aug-11 16:45 
GeneralRe: Put resource in same exe folder Pin
milan1-Aug-11 20:55
milan1-Aug-11 20:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.