Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Silverlight » Silverlight DatePicker Control

Silverlight DatePicker Control

A DatePicker control is used to create a visual DatePicker that let user to pick a date and fire an event on the selection of the date. This article demonstrates how to create and use a DatePicker control in Silverlight with the help of XAML and C#.

Author Rank :
Page Views : 36609
Downloads : 351
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DatePickerSample.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


A DatePicker control is used to create a visual DatePicker that let user to pick a date and fire an event on the selection of the date. This article demonstrates how to create and use a DatePicker control in Silverlight with the help of XAML and C#.

Creating a DatePicker

The DatePicker element represents a Silverlight DatePicker control in XAML.

 

<DatePicker/>

 

The DatePicker control is defined in the System.Windows.Controls namespace. When you drag and drop a DatePicker control from Toolbox to the page, you will notice the following namespace is added to the top of the page.

 

xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

 

And following code is added for the DatePicker control.

 

<basics:DatePicker></basics:DatePicker>

 

The default view of the DatePicker control looks like Figure 1.

 

DPImg1.gif
Figure 1

The Width and Height attributes of the DatePicker element represent the width and the height of a DatePicker. The Content attribute represents the text of a DatePicker.  The x:Name attribute represents the name of the control, which is a unique identifier of a control.

 

The code snippet in Listing 1 creates a DatePicker control and sets the name, height, and width properties of a DatePicker control.

 

<DatePicker x:Name=" DatePicker1" Height="30" Width="100" >

</DatePicker>

Listing 1

Display Date

The DisplayDate property represents the date to display. The default is today.

IsDropDownOpen

The IsDropDownOpen property indicates if the calendar part of the DatePicker control is open or closed.  

Text Property

The Text property represents the text that is displayed in the DatePicker.  

Selection Date and Selection Date Format

The SelectedDate property represents the currently selected date. If multiple dates selection is true, the SelectedDates property represents a collection of currently selected dates.

BlackoutDates

The BlackoutDates property of the DatePicker class represents a collection of dates that are not available for selection. All non selection dates are marked by a cross. For example, say in Jan month of year 2009, we would like to block dates from Jan 1st to Jan 4th and then all Saturdays and Sundays and the final DatePicker should look like Figure 2.

DPImg2.gif

Figure 2

We can achieve this by adding code listed in Listing 2. As you can see from Listing 3, the BlackoutDates.Add method takes a DatePickerDateRange object, which is a collection of two DateTime objects. The first date is the start date of the range and second date is the end date of the date range.

private void SetBlackOutDates()

{

    MonthlyDatePicker.BlackoutDates.Add(new DatePickerDateRange(

        new DateTime(2009, 1, 1),

        new DateTime(2009, 1, 4)

        ));

    MonthlyDatePicker.BlackoutDates.Add(new DatePickerDateRange(

        new DateTime(2009, 1, 10),

        new DateTime(2009, 1, 11)

        ));

    MonthlyDatePicker.BlackoutDates.Add(new DatePickerDateRange(

      new DateTime(2009, 1, 17),

      new DateTime(2009, 1, 18)

      ));

    MonthlyDatePicker.BlackoutDates.Add(new DatePickerDateRange(

      new DateTime(2009, 1, 24),

      new DateTime(2009, 1, 25)

      ));

    MonthlyDatePicker.BlackoutDates.Add(new DatePickerDateRange(

      new DateTime(2009, 1, 31),

      new DateTime(2009, 1, 31)

      ));

}

Listing 2

DisplayDateStart and DisplayDateEnd

The DatePicker control allows you to set the start and end display dates by using the DisplayDateStart and DisplayDateEnd properties. If you see Figure 5 in the previous section, you may notice the Jan 2009 month DatePicker display start with Dec 28, 2008 date. But now what if you want to display dates for Jan 2009 month only? We can use the DisplayStartDate and DisplayEndDate properties to control the start and end dates of a month. The code listed in Listing 3 makes sure the start date is Jan 01, 2009 and end date is Jan 31, 2009. The current selected date is Jan 05.

private void SetDisplayDates()

{

    MonthlyDatePicker.DisplayDate = new DateTime(2009, 5, 1);

    MonthlyDatePicker.DisplayDateStart = new DateTime(2009, 1, 1);

    MonthlyDatePicker.DisplayDateEnd = new DateTime(2009, 1, 31);

}

Listing 3

The new DatePicker looks like Figure 3.

DPImg3.gif

Figure 3

FirstDayOfWeek and IsTodayHighlighted

By default, Sunday is the first day of week. If you would like to change it, you use FirstDayOfWeek property. The IsTodayHightlighted property is used to make today highlighted. The following code snippet sets the FirstDayOfWeek to Monday and makes today hightlited.

MonthlyDatePicker.FirstDayOfWeek = DayOfWeek.Monday;

MonthlyDatePicker.IsTodayHighlighted = true;

The new DatePicker looks like Figure 4, where you can see the start day of the week us Sunday.

DPImg4.gif

Figure 4

DatePicker Events

Besides the normal control events, the DatePicker control has three events DatePicker related events. These events are the DisplayDateChanged, DisplayModeChanged, and SelectedDatesChanged. The DisplayDateChanged event is fired where the DisplayDate property is changed. The DisplayModeChanged event is fired when the DisplayMode property is changed. The SelectedDatesChanged event is fired when the SelectedDate or SelectedDates properties are changed. The following code snippet sets these three events attributes.

<basics:DatePicker SelectionMode="SingleRange"

                 x:Name="MonthlyDatePicker"

                 SelectedDatesChanged="MonthlyDatePicker_SelectedDatesChanged"

                 DisplayDateChanged="MonthlyDatePicker_DisplayDateChanged"

                 DisplayModeChanged="MonthlyDatePicker_DisplayModeChanged"

                 HorizontalAlignment="Left"

                 VerticalAlignment="Top"

                 Margin="10,10,0,0">           

</basics:DatePicker>

The code behind for these events looks like Listing 4.

private void MonthlyDatePicker_SelectedDatesChanged(object sender,

    SelectionChangedEventArgs e)

{

}

 

private void MonthlyDatePicker_DisplayDateChanged(object sender,

    DatePickerDateChangedEventArgs e)

{

 

}

 

private void MonthlyDatePicker_DisplayModeChanged(object sender,

    DatePickerModeChangedEventArgs e)

{

 

}

Listing 4

Normally, on a date selection, you may want to capture that event and know what the current selected date is. Now how about we add a TextBox control to the page and on the date selection, we are going to set the text of the TextBox to the currently selected date.

We add the following code to the XAML just below the DatePicker control.

<TextBox Width="200" Height="50"

         VerticalAlignment="Bottom"

         HorizontalAlignment="Left"

         Margin="10,10,10,10"

         x:Name="SelectedDateTextBox">

   

</TextBox>

On the SelectedDateChanged event handler, we set the TextBox.Text property to the SelectedDate property of the DatePicker control as you can see from code in Listing 5.

private void MonthlyDatePicker_SelectedDatesChanged(object sender,

    SelectionChangedEventArgs e)

{

    SelectedDateTextBox.Text = MonthlyDatePicker.SelectedDate.ToString();

}

Listing 5

Now when you run the application, you will see output looks like Figure 5. When you select a date in the DatePicker, it will be displayed in the textbox.

DPImg5.gif

Figure 5

Formatting a DatePicker

How about we create a DatePicker control with a border formatting, background, and foreground of the DatePicker?

The BorderBrush property of the DatePicker sets a brush to draw the border of a DatePicker. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of red and blue color.

<basics:DatePicker.BorderBrush>

    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >

        <GradientStop Color="Blue" Offset="0" />

        <GradientStop Color="Red" Offset="1.0" />

    </LinearGradientBrush>

</basics:DatePicker.BorderBrush>

 

The Background and Foreground properties of the DatePicker set the background and foreground colors of a DatePicker. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a DatePicker.

<basics:DatePicker.Background>

    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >

        <GradientStop Color="Blue" Offset="0.1" />

        <GradientStop Color="Orange" Offset="0.25" />

        <GradientStop Color="Green" Offset="0.75" />

        <GradientStop Color="Red" Offset="1.0" />

    </LinearGradientBrush>

</basics:DatePicker.Background>

<basics:DatePicker.Foreground>

    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >

        <GradientStop Color="Black" Offset="0.25" />

        <GradientStop Color="Green" Offset="1.0" />

    </LinearGradientBrush>

</basics:DatePicker.Foreground>

The new DatePicker looks like Figure 6.

DPImg6.gif

Figure 6

Setting Image as Background of a DatePicker

To set an image as background of a DatePicker, we can set an image as the Background of the DatePicker. The following code snippet sets the background of a DatePicker to an image. The code also sets the opacity of the image.

<basics:DatePicker.Background>

    <ImageBrush ImageSource="Garden.jpg" Opacity="0.3"/>

</basics:DatePicker.Background>

The new output looks like Figure 7.

DPImg7.gif

Figure 7

Creating a DatePicker Dynamically

The code listed in Listing 6 creates a DatePicker control programmatically. First, it creates a DatePicker object and sets its DisplayMode and SelectedMode properties and later the DatePicker is added to the LayoutRoot.

private void CreateDynamicDatePicker()

{

    DatePicker cal = new DatePicker();

    cal.DisplayMode = DatePickerMode.Year;

    cal.SelectionMode = DatePickerSelectionMode.SingleDate;

 

    LayoutRoot.Children.Add(cal);

}

Listing 6

Summary

In this article, I discussed how we can create a DatePicker control in Silverlight and C#.  We also saw how to set display modes, selection modes, blackout dates, selected dates, border, background, and foreground properties. After that, we saw you to set an image as the background of a DatePicker. In the end of this article, we saw how to create a DatePicker dynamically.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
Silverlight by Nikhil On April 15, 2009
Hi, Sir, please tell me in brief what is silverlight, by which software i can use it, what is the use of silverlight...etc thnks Sir, i have post three articles long ago but they are not publishing ...please try to publish them soon... bez i want to post more and more.. thnks nikhil.kmr.johar@gmai.com
Reply | Email | Modify 
Re: Silverlight by Mahesh On April 15, 2009
Hi Nikhil,
Thank you for sharing your articles with us. However, due to the quality of the contents, we may not approve all articles. To ensure you get all articles approved, you need to make sure your articles are well written in a tutorial format and code is explained well. See this article format for example.

If you have any article that is not good enough for article, you may want to post that as a blog entry on the Blogs section.

Silverlight is new technology to build Web applications. It's basically the future of ASP.NET and provides many new features and controls that ASP.NET does not have.

See Silverlight section by clicking on Siliverlight link at the top or on home page to learn more about SL. We have hundreds of articles and tutorials on SL already.

Keep up the good work.
Cheers!

Mahesh
Reply | Email | Modify 
Re: Re: Silverlight by Nikhil On April 15, 2009
Thank you sir for replying me...

But you can see my articles these are not bad...
My Backup utility software is not bad sir, you can check sir,
but i will improve my submitting way ..
thanks a lot sir !
Nikhil Kumar
Reply | Email | Modify 
SelectionMode for DatePicker in Silverlight Beta 3.0 by Pravin On June 15, 2009
Hi,
I am using Silverlight Beta 3 for development. I don't see any property called as 'SelectionMode' for a DatePicker, although its present for Calendar. The last few lines of your code show the SelectionMode property for DatePicker. Can you please let me know which version of Silverlight are you using?
Reply | Email | Modify 
Re: SelectionMode for DatePicker in Silverlight Beta 3.0 by Mahesh On June 16, 2009
I used Silverlight Toolkit for this control. I am not sure if Beta has it or not. Microsoft keep changing their controls in every version.
Reply | Email | Modify 
Re: Re: SelectionMode for DatePicker in Silverlight Beta 3.0 by danny On October 28, 2009
great write up!
I'm gonna use something like this in the new app I'm working on, thanks again!

-----------------------------
Danny, San Francisco Locksmith
Reply | Email | Modify 
ReadOnly Property by saranya On February 4, 2010
Hi Sir,

Could u please tell me how to make the textbox of the datepicker control alone noneditable.There is no Readonly property for this control.

Thanks in Advance
Reply | Email | Modify 
Data picker by shital On September 27, 2011
HI I design the datapicker and I want to change default color of mouse over .how to change it?
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.