top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Various Types of Panels in XAML Layout using for WindowsPhone Application?

+4 votes

Why XAML is Important

XAML is a modern UI design Markup Language, it helps design a rich UI, 2d and 3d animation, plugin based applications and we also use XAML for:

  • Defining workflow content in Windows Workflow Foundation.
  • Defining services in Windows Communication Foundation.
  • A UI for Silverlight and Windows Presentation Foundation.
  • Rich graphics and animation based application.
  • Arranging controls based on fixed pixel coordinates.

The following summarizes the differences among Windows, Web and XAML Layout applications.

Normal Windows Layout Application

  • Controls have fixed coordinates.
  • The Location property has x and y coordinates representing the upper-left corner of the control retrieve to upper-left corner of container.
  • Some flexibility to dock the ok and cancel buttons to the lower right.
  • Anchor a list box to the left of the form using flow layout to arrange controls in a flow layout.
  • Use table layout to arrange controls in a table format.

Web Form Layout

  • Controls are, by default, anchored relative to the upper-left of the page.
  • You can specify absolute positioning if you want.
  • Re-sizing a window does not change the position of controls.

XAML Layout

  • XAML provides a rich set of built-in layout panels that help you to avoid the common pitfalls.
  • Flow Based Layout.
  • Content is organized in a Container.
  • All Containers are derived from Systems.Window.control.
  • Resolution and Size Independency.
  • Layout automatically adjusts if the screen resolution changes.

Element Size in XAML

  • The size can be specified as an absolute amount of logical units, as a percentage value or automatically.
  • Size is determined by calculating the available screen space, size of constraints and layout-specific properties (Margin, Padding, etc.) behavior of the present Panel.
  • Fixed size of logical units (1/96 inch).
  • Auto takes as much space as needed by the contained control.
  • Star (*) takes as much space as available (after filling all auto and fixed sized columns), proportionally divided over all star-sized columns. So 3*/5* means the same as 30*/50*.

Remember that star-sizing does not work if the grid size is calculated based on its content.

Panels in XAML

  • Grid Panel.
  • Stack Panel.
  • Dock Panel.
  • Wrap Panel.
  • Canvas Panel.

Grid Panel: combination of row and column layout is a Grid Panel; in other words, a Grid Panel arranges controls in a tabular format. The functionality is similar to the HTML table but more flexible as in the following example we try to show a row and column combination for the windows. There are 4 rows and 4 columns.

  • Row and Column definitions in a grid indicate row and column. If you create additional rows and columns, you have to add RowDefinition items to the RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection, as the above example shows a grid with 4 rows and 4 columns.

Add controls in Grid Panel

To add controls to the grid layout panel ,just put the declaration between the opening and closing tags of the Grid. Keep in mind that the row and columndefinitions must proceed any definition of child controls.

The grid layout panel provides the two attached properties Grid.Column and Grid.Row to define the location of the control.

In the following example I try to show one normal data entry form design using XAML:


StackPanel is a useful XAML layout. It keeps a control horizontal and vertical; using a stack we design the application like many controls.

Stack Panel common properties are:

  • Stack child element horizontally or vertically.
  • Default is vertical.
  • Use orientation to change to horizontal.
  • Controls positioning of elements by setting their horizontal alignment or vertical alignment properties.
  • Control spacing by setting a margin and padding properties of elements.

Wrap Panel

In a Wrap Panel the child elements are positioned sequentially, from left to right and top to bottom.

By default the layout orientation is horizontal and the controls flow left to right; depending on the screen size the control might wrap to the next line.

By default the screen and code:

        <WrapPanel Grid.Row="0" Grid.Column="0">
            <Button Margin="10">Mango</Button>
            <Button Margin="10">Apple</Button>
            <Button Margin="10">Grape</Button>
            <Button Margin="10">Banana</Button>
            <Button Margin="10">Bilberry</Button>
            <Button Margin="10">Lemon</Button>

Elements wrap to the next line once to reduce screen width:

DockPanel: Dock Panel is a most useful layout panel in XAML, it arranges controls to the top, left, bottom, right and remaining space. A useful property is:

  • DockPanel.Dock Property indicates where the element controls are docked.

The default is left; if we don't set the dock property then it will be left:

  • DockPanel.lastChildFill DockPanel will fill up the remaining space of the window.

Canvas Layout:

  • Elements are placed according to coordinates
  • The Canvas layout is similar to Windows forms layout.
  • Elements do not resize automatically at run time.
  • Use canvas.left, canvas.right, and canvas.buttom.


  • Time consuming and laborious.
  • Harder to line up elements.
  • No resolution and size independence.


            <Label Content="Canvas Layout Demo"  FontSize="15" FontWeight="Bold"
                    Foreground="Red"  Canvas.Top="10" Canvas.Left="25"/> 
            <Label Content="ContactInfo" FontSize="12"  Canvas.Top="66" Canvas.Left="10"/> 
            <Label Content="Name"  Canvas.Top="45" Canvas.Left="93"/> 
            <Label Content="Address"  Canvas.Top="90" Canvas.Left="93"/>
            <TextBox  FontSize="15" FontWeight="Bold"         Canvas.Top="45" Canvas.Left="185" Width="93"/>
            <TextBox FontSize="15" FontWeight="Bold"          Canvas.Top="90" Canvas.Left="185" Width="93"/>

One small simple Data Entry Form Demo using all panels: stack, dock, wrap, and canvas.

In this example we try to show the real use of these panels and controls in WPF:


posted Jan 21, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

Related Articles

I am building a website in XAML (Silverlight) and trying to put prototype samples together to see what can be done in Silverlight and what obstacles will I face in building samples that can easily be done in ASP.NET 2.0. One piece of this was to create an animated banner that shows some ads and give text animations such as changing colors, rotation, and size.

In a graphics designer, you create layers and frames and give them a time interval to load a different layer to create an animated graphics. Fortunately, this functionality is built-in in WPF and XAML. Now, I don't have to create different layers or frames. I can simply create a text and apply animation or transformation on the text and WPF will take care for me. 

I have a banner looks like Figure 1.


Figure 1. Initial banner

As you can see from Figure 1, I have four text blocks loaded in the banner and two of them are with a gradient background. I would apply four different animations on these four text blocks. I would change the gradient background of first text block, change the foreground color of second text block, change the width of third text block, and rotate the fourth text block. The running banner will look like Figure 2 and repeat this behavior indefinitely.



Figure 2. Animated text banner

The magic begins within the Storyboard tag of XAML. Within the Storyboard tag, we can use animations such as double animation, color animation, point animation, or transformation.


      <EventTrigger RoutedEvent="FrameworkElement.Loaded">








The DoubleAnimation tag is used to apply transparency on controls. The following code shows the syntax of the DoubleAnimation. The TargetName is the name of the control such as a TextBlock. The From and To attributes is the range for transparency range between 1.0 and 0.0 where 1.0 is fully opaque and 0.0 is fully transparent.  The RepeatBehavior is Forever means the animation will repeat forever.


      Storyboard.TargetName="TB"                                 Storyboard.TargetProperty="Opacity"

      From="1.0" To="0.0" Duration="0:0:5"

      AutoReverse="True" RepeatBehavior="Forever" />

The following code shows how to user color animation using the ColorAnimation tag, which takes TargetName as name of the brush and TargetProperty as Color. The From and To attributes are starting and end colors.




From="Pink" To="SteelBlue" Duration="0:0:5"

AutoReverse="True" RepeatBehavior="Forever" />

The following code usage double animation to set the transformation angle of the text box to rotate a text block.




      From="0.0" To="360" Duration="0:0:10"

RepeatBehavior="Forever" />

Download the attached XAML file for more details and complete XAML code.  

Here is a listing of complete XAML code:







      Width="396" Height="492"xmlns:d=""xmlns:mc=""mc:Ignorable="d" Foreground="#FFF15151" SnapsToDevicePixels="True" >


      <Grid x:Name="LayoutRoot">

            <Rectangle Margin="66,42,152,20" Stroke="#FF000000" RadiusX="0"RadiusY="0">


                        <LinearGradientBrush x:Name="MRGB" EndPoint="0.5,1"StartPoint="0.5,0">

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FF5E0805" Offset="0.478"/>





      <TextBlock x:Name="TB" Margin="75,49,161,0" FontFamily="Book Antiqua"FontSize="24" FontWeight="Bold" TextWrapping="Wrap" Foreground="#FFF9F4F4"TextAlignment="Center" Height="56" VerticalAlignment="Top" ><TextBlock.Background>

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

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FFD600FF" Offset="1"/>




                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">






                                                From="1.0" To="0.0"Duration="0:0:5"

                                                AutoReverse="True"RepeatBehavior="Forever" />




                  </TextBlock.Triggers><Run FontFamily="Cambria" FontSize="20"Text="Need help on a .NET Project? "/></TextBlock>

            <TextBlock x:Name="TB2" Margin="75,225,161,131" FontFamily="Book Antiqua" FontSize="24" FontWeight="Bold" TextWrapping="Wrap" Foreground="#FFF9F4F4"TextAlignment="Center"><TextBlock.Background>

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

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FF00FF4D" Offset="1"/>



                  <LineBreak/><Run FontFamily="Cambria" FontSize="20"Foreground="#FF97ECC3" Text="Let our experts help you."/>


                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">









            <!-- Color Animation Sample. Changes color from Pink to SteelBlue -->



              Margin="75,120,161,0" FontSize="16" FontWeight="Bold"VerticalAlignment="Top"

              Height="100" Text="Silverlight, C#, ASP.NET, WPF, WCF"TextWrapping="WrapWithOverflow" TextAlignment="Center">


                <SolidColorBrush x:Name="SB" Color="Pink" />



              <!-- Animates the text block's color. -->


                <EventTrigger RoutedEvent="FrameworkElement.Loaded">



                        <!-- Use ColorAnimation with TargetProperty as Color and TargetName as brush being used

                        to draw the text -->




                        From="Pink" To="SteelBlue" Duration="0:0:5"

                        AutoReverse="True" RepeatBehavior="Forever" />








            <!-- Text Rotation Sample -->




              FontSize="18" FontWeight="Bold" Foreground="Green"VerticalAlignment="Bottom" Height="60"><TextBlock.RenderTransform>

                <RotateTransform x:Name="MyRT" Angle="0" CenterX="30"CenterY="25"/>

              </TextBlock.RenderTransform><!-- Animates the text block's rotation. --><TextBlock.Triggers>

                <EventTrigger RoutedEvent="FrameworkElement.Loaded">



                        <!-- Use DoubleAnimation with TargetProperty as RotateTransform.Angle

                              and TargetName as name of the RotateTransform being used to rotate the text -->




                        From="0.0" To="360" Duration="0:0:10"

                        RepeatBehavior="Forever" />




              </TextBlock.Triggers><Run FontSize="20" Text="Contact Us"/></TextBlock>


            <!-- Author TextBlok -->





We can use the Arc XAML element to draw arcs in XAML. Besides drawing arcs using the Arc element, we can also use the ArcSegment element. The ArcSegment is useful when an arc becomes a part of a graphics path or a larger geometric object.


In this article, we will see how to use the ArcSegment to draw arcs in XAML and WPF.


The ArcSegment object represents an elliptical arc between two points. The ArcSegment class has the five properties Point, Size, SweepDirection, IsLargeArc and RotationAngle. 


  • The Point property represents the endpoints of an arc. 
  • The Size property represents the x and y radiuses of an arc. 
  • The SweepDirection property specifies whether an arc sweep direction is clock wise or counter clock wise. 
  • The IsLargeArc property returns true if an arc is greater than 180 degrees. 
  • The RotationAngle property represents the angle by which an ellipse is rotated about the x-axis.



The following figure provided by the MSDN documentation shows these property values and their results.


<ArcSegment Size="300,50" RotationAngle="30" 
            IsLargeArc="True" SweepDirection="CounterClockwise"  Point="200,100" />

A Path object is used to draw an arc by setting a PathGeomerty as Path.Data. The following code snippet creates a Path and sets a ArcSegment as a part of PathFigure.Segments.

<Path Stroke="Black" StrokeThickness="1">
                    <PathFigure StartPoint="0,100">
                                <ArcSegment Size="300,50" RotationAngle="30"
                                            Point="200,100" />

The output looks like Figure 1.



Figure 1

We can paint an arc by simply painting the path using the Fill method. The following code snippet has changes in it from the previous code that fills a path. 

<Path Stroke="Black" StrokeThickness="1" Fill="Yellow">

The new output looks like Figure 2.



Figure 2

The following code snippet creates an arc segment shown in Figure 2 dynamically.

private void CreateArcSegment()
    PathFigure pthFigure = new PathFigure();
    pthFigure.StartPoint = new Point(0, 100); 

    ArcSegment arcSeg = new ArcSegment();
    arcSeg.Point = new Point(200, 100);
    arcSeg.Size = new Size(300,50);
    arcSeg.IsLargeArc = true;
    arcSeg.SweepDirection = SweepDirection.Counterclockwise;
    arcSeg.RotationAngle = 30;   

    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();

    pthFigure.Segments = myPathSegmentCollection; 

    PathFigureCollection pthFigureCollection = new PathFigureCollection();

    PathGeometry pthGeometry = new PathGeometry();
    pthGeometry.Figures = pthFigureCollection; 

    Path arcPath = new Path();
    arcPath.Stroke = new SolidColorBrush(Colors.Black);
    arcPath.StrokeThickness = 1;
    arcPath.Data = pthGeometry;
    arcPath.Fill = new SolidColorBrush(Colors.Yellow); 




XAML is mostly used at design-time but there may be a time when you want to create XAML dynamically and/or load XAML in your code. The XamlWriter and the XamlReader classes are used to create and read XAML in code.

The XamlWriter and the XamlReader classes are defined in the System.Windows.Markup namespace and must be imported to use the classes as in the following:

using System.Windows.Markup;

The XamlWriter.Save method takes an object as an input and creates a string containing the valid XAML.

The code snippet in Listing 1 creates a Button control using code and saves it in a string using the XamlWriter.Save method.


// Create a Dynamic Button.

Button helloButton = new Button();

helloButton.Height = 50;

helloButton.Width = 100;

helloButton.Background = Brushes.AliceBlue;

helloButton.Content = "Click Me";


// Save the Button to a string.

string dynamicXAML = XamlWriter.Save(helloButton);


Listing 1

The XamlReader.Load method reads the XAML input in the specified Stream and returns an object that is the root of the corresponding object tree.

The code snippet in Listing 2 creates a XmlReader from a XAML and then creates a Button control using the XamlReader.Load method.


// Load the button

XmlReader xmlReader = XmlReader.Create(new StringReader(dynamicXAML));

Button readerLoadButton = (Button)XamlReader.Load(xmlReader);   

Listing 2


The GroupBox element in XAML is used to add a header to an area and within that area you can place controls. By default, a GroupBox can have one child but multiple child controls can be added by placing a container control on a GroupBox such as a Grid or StackPanel.

How to create a GroupBox in WPF and Windows phone application,.

The GroupBox element in XAML represents a GroupBox control. The following code snippet creates a GroupBox control and sets its background and font. The code also sets the header using GroupBox.Header. 

  1. <Window x:Class="GroupBoxSample.Window1"  
  2.     xmlns=""  
  3.     xmlns:x=""  
  4.     Title="Window1" Height="300" Width="300">  
  5.     <Grid>  
  6.         <GroupBox Margin="10,10,10,10" FontSize="16" FontWeight="Bold"  
  7.                   Background="LightGray">  
  8.             <GroupBox.Header>                  
  9.                Mindcracker Network  
  10.             </GroupBox.Header>   
  12.             <TextBlock FontSize="12" FontWeight="Regular">  
  13.                 This is a group box control content.                  
  14.             </TextBlock>               
  16.         </GroupBox>  
  18.     </Grid>  
  19. </Window>  

The output looks like this.


Calendar Events

Besides the normal control events, the Calendar control has three events calendar 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. 

<Calendar SelectionMode="SingleRange"  

The code behind for these events look as in Listing 4. 

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
private void MonthlyCalendar_DisplayDateChanged(object sender,   
    CalendarDateChangedEventArgs e)  
private void MonthlyCalendar_DisplayModeChanged(object sender,   
    CalendarModeChangedEventArgs 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 will set the text of the TextBox to the currently selected date. 

We add the following code to the XAML just below the Calendar control. <TextBox Width="200" Height="30"  

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

private void MonthlyCalendar_SelectedDatesChanged(object sender,   
    SelectionChangedEventArgs e)  
    SelectedDateTextBox.Text = MonthlyCalendar.SelectedDate.ToString();  

Listing 5

Now when you run the application, you will see the output that looks as in Figure 10. When you select a date in the Calendar, it will be displayed in the TextBox. 

Figure 10

Formatting a Calendar

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

The BorderBrush property of the Calendar sets a brush to draw the border of a Calendar. 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 the colors Red and Blue.

   <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
      <GradientStop Color="Blue" Offset="0" />  
      <GradientStop Color="Red" Offset="1.0" />  

The Background and Foreground properties of the Calendar set the background and foreground colors of a Calendar. 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 Calendar. 

    <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 StartPoint="0,0" EndPoint="1,1" >  
        <GradientStop Color="Black" Offset="0.25" />  
        <GradientStop Color="Green" Offset="1.0" />  

The new Calendar looks as in Figure 11. 

Figure 11

Setting Image as Background of a Calendar

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

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

The new output looks as in Figure 12.

Figure 12

Creating a Calendar Dynamically

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

private void CreateDynamicCalendar()  
    Calendar MonthlyCalendar = new Calendar();  
    MonthlyCalendar.Name = "MonthlyCalendar";  
    MonthlyCalendar.Width = 300;  
    MonthlyCalendar.Height = 400;  
    MonthlyCalendar.Background = Brushes.LightBlue;  
    MonthlyCalendar.DisplayMode = CalendarMode.Month;  
    MonthlyCalendar.SelectionMode = CalendarSelectionMode.SingleRange;  
    MonthlyCalendar.DisplayDateStart = new DateTime(2010, 3, 1);  
    MonthlyCalendar.DisplayDateEnd = new DateTime(2010, 3, 31);  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 5));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 15));  
    MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 25));    
    MonthlyCalendar.FirstDayOfWeek = DayOfWeek.Monday;  
    MonthlyCalendar.IsTodayHighlighted = true;    

Listing 6


In this article, I discussed the calendar control using XAML 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 Calendar. In the end of this article, we saw how to create a Calendar dynamically.


The following code snippet adds blackout dates to a Calendar. 

   <CalendarDateRange Start="3/1/2010" End="3/7/2010"/>  
   <CalendarDateRange Start="3/8/2010" End="3/8/2010"/>  
   <CalendarDateRange Start="3/15/2010" End="3/15/2010"/>  
   <CalendarDateRange Start="3/22/2010" End="3/22/2010"/>  
   <CalendarDateRange Start="3/29/2010" End="3/29/2010"/>  

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

private void SetBlackOutDates()  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
        new DateTime(2010, 3, 1),  
        new DateTime(2010, 3, 7)  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
        new DateTime(2010, 3, 8),  
        new DateTime(2010, 3, 8)  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 15),  
      new DateTime(2010, 3, 15)  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 22),  
      new DateTime(2010, 3, 22)  
    MonthlyCalendar.BlackoutDates.Add(new CalendarDateRange(  
      new DateTime(2010, 3, 29),  
      new DateTime(2010, 3, 29)  

Listing 2

DisplayDateStart and DisplayDateEnd

The Calendar control allows you to set the start and end display dates using the DisplayDateStart and DisplayDateEnd properties. If you see Figure 5 in the previous section, you may notice the March 2010 month calendar display starts with the March 01, 2010 date. But now, what if you want to display the dates for only the month of March 2010? We can use the DisplayStartDate and DisplayEndDate properties to control the start and end dates of a month. 

DisplayDate property represents the current date to display. 

The following code snippet sets the DisplayDate, DisplayDateStart and DisplayDateEnd attributes of the Calendar element in XAML.

<Calendar Name="MonthlyCalendar"   

The code listed in Listing 3 makes sure the start date is March 01, 2010 and end date is March 31, 2010. The current selected date is March 05. 

private void SetDisplayDates()  
   MonthlyCalendar.DisplayDate = new DateTime(2010, 3, 5);  
   MonthlyCalendar.DisplayDateStart = new DateTime(2010, 3, 1);  
   MonthlyCalendar.DisplayDateEnd = new DateTime(2010, 3, 31);  

Listing 3

The new calendar looks as in Figure 6. 

Figure 6

FirstDayOfWeek and IsTodayHighlighted

By default, Sunday is the first day of the week. If you would like to change it, you use the FirstDayOfWeek property. The IsTodayHightlighted property is used to highlight today. 

The following code snippet sets the FirstDayOfWeek to Tuesday and makes today highlighted.

<Calendar Name="MonthlyCalendar"   
   xmlns:sys="clr-namespace:System;assembly=mscorlib" Margin="15,39,88,19">  

The following code snippet sets the FirstDayOfWeek to Tuesday and makes today highlighted in WPF.

MonthlyCalendar.FirstDayOfWeek = DayOfWeek.Tuesday;  
MonthlyCalendar.IsTodayHighlighted = true;

The new calendar looks as in Figure 7, where you can see the start day of the week is Tuesday.

Figure 7

Selected Date and Selected Dates

The SelectedDate property represents the current selected date. If multiple date selection is true then the SelectedDates property represents all the selected dates in a Calendar. The following code snippet sets the SelectedDates in XAML at design-time. 

<Calendar Name="MonthlyCalendar"   
    xmlns:sys="clr-namespace:System;assembly=mscorlib" Margin="15,39,88,19">    

The selected dates in a Calendar looks as in Figure 8 where you can see March 5th, 15th and 25th have a light blue background and represents the selected dates. 

Figure 8

The following code snippet sets the SelectedDates property in WPF at run-time. 

private void AddSelectedDates()  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 5));  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 15));  
   MonthlyCalendar.SelectedDates.Add(new DateTime(2010, 3, 25));  

Note: If you have set the selected dates to any of the blackout dates, you will see the parser in XAML will throw an error as in Figure 9. 

Figure 9


A calendar control is used to create a visual calendar that lets users pick a date and fire an event on the selection of the date. This article demonstrates how to create and use a calendar control using XAML and C# in WPF.

Creating a Calendar

The Calendar element represents a calendar control in XAML as in the following:

  1. <Calendar/>  

The Calendar control is defined in the System.Windows.Controls namespace. When you drag and drop a Calendar control from the Toolbox to the page, the XAML code will look like the following code where you can see a Calendar XAML element has been added within the Grid element and its Width, Height, Name and VerticalAlignment and HorizontalAlignment attributes are set.

  1. <Grid>  
  2.    <Calendar Height="170" HorizontalAlignment="Left" Margin="58,32,0,0"   
  3.       Name="calendar1" VerticalAlignment="Top" Width="180" />  
  4. </Grid>  

The default view of the Calendar control looks as in Figure 1. 

Figure 1

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

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

  1. <Calendar Name=" MonthlyCalendar" Height="30" Width="100" >  
  2. </Calendar>  

Listing 1

Display Modes

The DisplayMode property of the Calendar class represents the format of the display of a Calendar, that can be a month, year, or decade. Month is the default mode. Setting the DisplayMode to Year and Decade generates Figure 2 and Figure 3 respectively. 

Figure 2

Figure 3

The Month view that is also the default view looks as in Figure 4.

Figure 4

If you use an example of the Decade and click on the year 2008 in Figure 3, you will get another Calendar format with all the months in the year 2008 and if you click on any month, you will eventually get the month view of the Calendar. 

The following code snippet sets the DisplayMode property to Decade. 

  1. <Calendar DisplayMode="Decade">   
  2. </Calendar>  

Selection Modes and Selection Dates

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

The SelectionMode of type CalendarSelectionMode enumeration represents the selection mode of calendar. Table 1 describes the CalendarSelectionMode enumeration and its members. 

NoneNo selections are allowed.
SingleDateOnly a single date can be selected, either by setting SelectedDate or the first value in SelectedDates. AddRange cannot be used.
SingleRangeA single range of dates can be selected. Setting SelectedDate, adding a date individually to SelectedDates, or using AddRange will clear all previous values from SelectedDates.
MultipleRangeMultiple non-contiguous ranges of dates can be selected. Adding a date individually to SelectedDates or using AddRange will not clear SelectedDates. Setting SelectedDate will still clear SelectedDates, but additional dates or range can then be added. Adding a range that includes some dates that are already selected or overlaps with another range results in the union of the ranges and does not cause an exception.

The following code snippet sets the SelectionMode property to a single range.

  1. <Calendar SelectionMode="SingleRange">  
  2. </Calendar>  


The BlackoutDates property of the Calendar 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 the month of March of the year 2010, we would like to block the dates from Jan 1st to Jan 7th and then all Sundays and the final calendar should look as in Figure 5.

Figure 5

Part 2 Continuous..

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.