Click here to Skip to main content
15,311,151 members
Articles / Web Development / ASP.NET
Posted 14 Feb 2009


89 bookmarked

Silverlight Gantt Chart

Rate me:
Please Sign up or sign in to vote.
4.85/5 (30 votes)
14 Feb 2009MIT6 min read
An example of a Gantt chart implemented in Silverlight 2.0.

Image 1


This project demonstrates implementing Gantt chart functionality in Silverlight. The primary purpose is to allow a user to quickly and easily enter data that relates to two elements. In this example, the two elements are date and person; however, the code can be adapted for other relations.

Features of the Gantt Chart

This Silverlight project is not a full featured Gantt chart such as Microsoft Project. It demonstrates only the most basic functionality, and is provided as a starting point for your own projects.

The features it includes are:

  • Displays a full year on a scrollable window
  • Allows a "Date Box" to be created for each day for up to 15 rows
  • The text for each date in the 15 rows can be changed
  • Each "Date Box" can be resized to add or subtract days
  • Each "Date Box" can be deleted
  • The "Date Boxes" on each row cannot overlap
  • When a year is changed, the "Day Boxes" entered on it are saved and redisplayed when the year is re-selected

The Layout

Image 2

The Silverlight Gantt chart is made up of the following elements:

  • ToolBar - A Silverlight Canvas control that slides to the right and left. It slides behind a "Clipping Window" called ToolBarWindow that only shows part of the ToolBar at a time.
  • Year Selector - A Silverlight ComboBox control that allows the year to be changed.
  • Scroll Bar - A Silverlight ScrollBar control that is programmatically linked to the ToolBar. It allows the user to move the ToolBar.
  • Row Label - A series of 15 Silverlight Textbox controls that provide a label for each ToolBar row.
  • Month Box - A series of 12 Silverlight controls that represent the months.
  • Day Box - A series of Silverlight controls that represent a day of the month. The controls are shaded when their day falls on a weekend.
  • Date Box - A Silverlight control that represents date(s) placed on the ToolBar.

The Grid

When the Silverlight Gantt control loads, it creates some default data:

#region CreateDefaultData
private void CreateDefaultData()
    colDateBoxAllYears = new List<datebox>();
    DateBox objDateBox = new DateBox(3, 
    DateBox objDateBox2 = new DateBox(4, 

It instantiates two DateBox controls, passing the row and the "Start Date" and the "End Date". It then adds these to a Generic List called colDateBoxAllYears.

#region DisplayYear
private void DisplayYear(string strYear)
    List<dateplannermonth> colDatePlannerMonths = 

    double StartPosition = (double)0;
    foreach (DatePlannerMonth objDatePlannerMonth in colDatePlannerMonths)
        AddMonthToToolbar(objDatePlannerMonth, strYear, StartPosition);
        StartPosition = StartPosition + objDatePlannerMonth.MonthWidth;

This collection is used when the DisplayYear method is called. This method adds the months and the days for the current year to the ToolBar (the Grid). It also adds the grid lines and any dates for the current year that are in the colDateBoxAllYears collection.

#region UpdateToolBarPosition
private void UpdateToolBarPosition(Point Point)
    double dCurrentPosition = (Point.X - StartingDragPoint.X);
    if ((dCurrentPosition < 0) & (dCurrentPosition > -8234))
        Canvas.SetLeft(ToolBar, Point.X - StartingDragPoint.X);
        ctlScrollBar.Value = dCurrentPosition * -1;

The ToolBar is moved by altering its Canvas.SetLeft position. ctlScrollBar.Value moves the ScrollBar control position so that it stays in sync with the ToolBar.

The ScrollBar

Image 3

The ScrollBar control moves the ToolBar using the following code:

#region ctlScrollBar_Scroll
private void ctlScrollBar_Scroll(object sender, 
        System.Windows.Controls.Primitives.ScrollEventArgs e)
    Point Point = new Point(e.NewValue, 0);
    Canvas.SetLeft(ToolBar, Point.X * -1);

Months and Days

Image 4

The MonthBox control is primarily composed of a Silverlight StackPanel control with 31 DayBox controls. When each month control is created, it is sized to only show the correct amount of days for the month it represents.

#region GetMonthWidth
private static double GetMonthWidth(DateTime dtMonthYear)
    // 31 days is 744
    double dWidth = 744;
    // Get the days in the Month
    int intDaysInMonth = DateTime.DaysInMonth(dtMonthYear.Year, 
    // Determine the difference between
    // 31 and the current days in the Month
    int intDaysToSubtract = (31 - intDaysInMonth);
    // If there is a difference subtract the days
    if (intDaysToSubtract > 0)
        // The Width of each day is 24 
        // Subtract 24 for each day
        dWidth = dWidth - (24 * intDaysToSubtract);
    return dWidth;

The ASP.NET DateTime.DaysInMonth method will automatically handle complex calculations such as leap years.

The Year DropDown

Image 5

When the year is changed, the following code executes:

#region dlYear_SelectionChanged
private void dlYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
    if (colDateBoxAllYears != null)
        // Get all the entries in the DateBox collections
        // that are not in the current Year
        List<datebox> colDateBoxNotCurrentYear = 
          colDateBoxAllYears.AsEnumerable().Where(x => x.DayBoxStart.Year != 

        // Get all the DateBoxes in the Toolbar canvas (The current year)
        List<datebox> colDateBoxCurrentYear = 
          ToolBar.Children.AsEnumerable().Where(x => x.GetType().Name == 

        // Build final collection
        colDateBoxAllYears = new List<datebox>();
        foreach (DateBox objDateBox in colDateBoxNotCurrentYear)
        foreach (DateBox objDateBox in colDateBoxCurrentYear)

        // Set the current year
        dtCurrentYear = 

The code uses LINQ to get all the DateBox controls in the colDateBoxAllYears collection that are not for the current year; it then uses LINQ to get the DateBox controls that are on the ToolBar (these are the boxes for the current year).

Image 6

It then combines the two to build a final collection. This is saved in the ccolDateBoxAllYears collection, and the newly selected year is then displayed.

The DateBox Control

Image 7

The DateBox control is used to indicate the dates selected on the ToolBar. It is composed of a Silverlight Rectangle with a Silverlight Canvas on the left side and the right site. The left and right side Canvases are used to determine when a user is trying to drag the control wider or smaller.

public DateBox(int parmBoxRow, DateTime parmDayBoxStart, DateTime parmDayBoxStop)
    // Required to initialize variables

    _BoxRow = parmBoxRow;
    _DayBoxStart = parmDayBoxStart;
    _DayBoxStop = parmDayBoxStop;

    TimeSpan tsBoxDaysDifference = _DayBoxStop - _DayBoxStart;
    int intBoxDays = tsBoxDaysDifference.Days;
    this.BoxSize = (intBoxDays * 24) + 24;

When the control is instantiated, the current row and start and stop dates are saved, and the width of the box is set based on the amount of days.

#region SetToolTip
private void SetToolTip()
    ToolTipService.SetToolTip(BoxRetangle, String.Format("{0} - {1}",

    ToolTipService.SetToolTip(LeftSideHandle, String.Format("{0} - {1}",

    ToolTipService.SetToolTip(RightSideHandle, String.Format("{0} - {1}",

It also uses the ToolTipService object to create the display that shows the dates for the DateBox when the user hovers the mouse over the elements.

private void LeftButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    // Get current Mouse position
    Point tmpPoint = e.GetPosition(null);
    // Build a list of elements at the current mouse position
    List<uielement> hits = 
        .FindElementsInHostCoordinates(tmpPoint, this);
    // Get all the DateBoxes in the Toolbar canvas
    List<datebox> colDateBox = ToolBar.Children.AsEnumerable().Where(
      x => x.GetType().Name == "DateBox").Cast<datebox>().ToList();
    // Loop through all the DateBoxes in the Toolbar canvas
    foreach (DateBox objDateBox in colDateBox)
        if (hits.Contains(objDateBox))
            Point DateBoxPoint = e.GetPosition(objDateBox);
            TimeSpan tsBoxDays = objDateBox.DayBoxStop - objDateBox.DayBoxStart;
            if (DateBoxPoint.X <= 2 || 
               (DateBoxPoint.X >= ((tsBoxDays.Days + 1) * 24) - 2))
                // Set the objResizingDateBox to the current
                // datebox so that it will be
                // resized when the mouse button is released
                objResizingDateBox = objDateBox;
                StartingCanvasDragPoint = GetMousePosition(ToolBar, e);

                // Save the side that is being resized
                if (DateBoxPoint.X <= 2)
                    strResizingDateBoxSide = ''Left'';
                    strResizingDateBoxSide = ''Right'';
                // The center of the DateBox was clicked. Show the Popup

When the user clicks on the ToolBar, the FindElementsInHostCoordinates method is used to find all the elements that are at the present mouse position. Note, the horizontal and vertical gridlines have IsHitTestVisible="false" to improve performance (it means they will be ignored).

If an existing DateBox is detected, the code checks to see if one of the sides of the DateBox is detected because that would indicate the user wishes to drag the DateBox wider or smaller.

// If the mouse did not move - Place a box on the grid           
if (CheckTolerance(StartingDragPoint, EndingDragPoint))
    Point objPoint = BoxClicked(EndingDragPoint);
    InsertBox(objPoint, 0);

When a user lifts the mouse button after clicking on the ToolBar and there are no other elements there, the CheckTolerance method is used to determine if the mouse moved more than two "points" in either direction.

#region InsertBox
private void InsertBox(Point objPoint, int intDays)
    int intX = Convert.ToInt32(objPoint.X);
    int intY = Convert.ToInt32(objPoint.Y);

    // Find position for the Box
    Point boxPoint = new Point((intX * 24 - 24), (intY * 24 - 28));

    // Only place a box if row is higher than 2
    if (intY > 2)
        DateBox objDateBox = new DateBox(intY, GetBoxDate(intX, GetSelectedYear()), 
            GetBoxDate(intX + intDays, GetSelectedYear()));
        Canvas.SetLeft(objDateBox, boxPoint.X);
        Canvas.SetTop(objDateBox, boxPoint.Y);


If the mouse did not move past the "tolerance", a new box is instantiated and added to the Toolbar using: ToolBar.Children.Add(objDateBox).

The Popup

Image 8

When the user clicks directly on a DateBox, the Popup control is used to display the date range of the DateBox and to allow the user the option to delete the DateBox.

#region CreatePopup
private void CreatePopup()
    objDateBoxPopup = new Popup();
    objDateBoxPopup.Name = "DeletePopup";
    objDateBoxPopup.Child = new DateBoxPopup();
    objDateBoxPopup.SetValue(Canvas.LeftProperty, 150d);
    objDateBoxPopup.SetValue(Canvas.TopProperty, 150d);
    objDateBoxPopup.HorizontalOffset = 25;
    objDateBoxPopup.VerticalOffset = 25;
    objDateBoxPopup.IsOpen = false;

When the Silverlight Gantt chart first loads, a Popup is created and a DateBoxPopup control is placed inside it.

#region ShowPopup
private void ShowPopup(DateBox objDateBox)
    if (objDateBoxPopup.IsOpen == false)
        DateBoxPopup GanttPopUpBox = 
        GanttPopUpBox.objDateBox = objDateBox;
        objDateBoxPopup.IsOpen = true;

When the Popup needs to appear, a instance of the associated DateBox is set as a property of the DateBoxPopup control (that is contained in the Popup).

#region btnDelete_Click
private void btnDelete_Click(object sender, RoutedEventArgs e)
    Canvas ToolBar = (Canvas)this.LayoutRoot.FindName("ToolBar");

If the Delete button is clicked, the DateBoxPopup control will already have an instance of the DateBox control so it can delete it by removing it from the ToolBar.

#region ClosePopup
private void ClosePopup()
    Popup objPopup = (Popup)this.LayoutRoot.FindName("DeletePopup");
    objPopup.IsOpen = false;

When the Popup is "closed", its IsOpen property is simply set to false.

The Power of the Mouse

The mouse is a very efficient input device. A user is able to move their hand and click much faster than they can usually type. A control such as a Gantt chart allows the user to indicate two things at one time with a single mouse click. In this example, the click represents:

  • "I want to set this person to be reserved on this day".

However, you can adapt this code to represent other things such as:

  • "I want this room reserved for these days".
  • "I want this product to be placed in this part of the store" (you would not use the MonthBoxes if you wanted to do this; instead, you would show each section of the store at the top of the control).

To Save you Some Time

Hopefully, this control will save you time when implementing your own Gantt chart functionality. Primarily, it saves you time because it performs the necessary calculations to prevent DateBoxes from overlapping.

To save the data, simply save the colDateBoxAllYears collection. To load the data, simply pass the colDateBoxAllYears collection to the control on start-up and the call the DisplayYear method.


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Software Developer (Senior)
United States United States
Michael Washington is a Microsoft MVP. He is a ASP.NET and
C# programmer.
He is the founder of,, and

He has a son, Zachary and resides in Los Angeles with his wife Valerie.

He is the Author of:

Comments and Discussions

GeneralMy vote of 5 Pin
RB Starkey19-Jan-11 10:39
professionalRB Starkey19-Jan-11 10:39 
QuestionMore rows Pin
mcosgeorge1-Mar-10 0:41
Membermcosgeorge1-Mar-10 0:41 
GeneralAnother Great Gantt Chart [modified] Pin
CoderForRent19-Mar-09 3:20
MemberCoderForRent19-Mar-09 3:20 
GeneralRe: Another Great Gantt Chart Pin
defwebserver19-Mar-09 3:43
Memberdefwebserver19-Mar-09 3:43 
GeneralNice article Pin
prady197518-Mar-09 22:13
Memberprady197518-Mar-09 22:13 
GeneralGreat work! Pin
hankar16-Feb-09 19:55
Memberhankar16-Feb-09 19:55 
GeneralMy vote of 2 Pin
shogunz0r16-Feb-09 9:49
Membershogunz0r16-Feb-09 9:49 
GeneralRe: My vote of 2 Pin
defwebserver17-Feb-09 4:25
Memberdefwebserver17-Feb-09 4:25 
GeneralRe: My vote of 2 Pin
trkchk17-Feb-09 15:02
Membertrkchk17-Feb-09 15:02 
GeneralDateTime Format Issues Pin
Dejan Petrovic15-Feb-09 0:11
MemberDejan Petrovic15-Feb-09 0:11 
GeneralRe: DateTime Format Issues Pin
defwebserver15-Feb-09 2:38
Memberdefwebserver15-Feb-09 2:38 
GeneralGreat control Pin
Jani Giannoudis14-Feb-09 20:55
MemberJani Giannoudis14-Feb-09 20:55 
GeneralRe: Great control Pin
defwebserver15-Feb-09 2:44
Memberdefwebserver15-Feb-09 2:44 

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.