top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to use TreeView in XAML and Windows phone application?

+3 votes
537 views

The XAML TreeView element represents a TreeView control. This tutorial shows you how to use aTreeView in WPF

Introduction 

TreeView represents data in a hierarchical view in a parent-child relationship where a parent node can be expanded or collapsed. The left side bar of Windows Explorer is an example of a TreeView.

The TreeView tag represents a WPF TreeView control in XAML

  1. <TreeView></TreeView>  

The Width and Height properties represent the width and the height of a TreeView. The Name property represents the name of the control that is a unique identifier of a control. The Margin property specifies the location of a TreeView on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments. 

The following code snippet sets the name, height and width of a TreeView control. The code also sets horizontal alignment to left and vertical alignment to top. 

  1. <TreeView Margin="10,10,0,13" Name="TreeView1" HorizontalAlignment="Left"   
  2. VerticalAlignment="Top" Width="194" Height="200" />  

Adding TreeView Items

TreeView control hosts a collection of TreeViewItems. The Header property is the text of the item that is displayed on the view. The following code snippet adds a parent item and six child items to a TreeViewcontrol. 

  1. <TreeView Margin="10,10,0,13" Name="TreeView1" HorizontalAlignment="Left"   
     VerticalAlignment="Top" Width="194" Height="200">  
        <TreeViewItem Header="Cold Drinks">  
            <TreeViewItem Header="Coke"></TreeViewItem>  
            <TreeViewItem Header="Pepsi"></TreeViewItem>  
            <TreeViewItem Header="Orange Juice"></TreeViewItem>  
            <TreeViewItem Header="Milk"></TreeViewItem>  
            <TreeViewItem Header="Iced Tea"></TreeViewItem>  
            <TreeViewItem Header="Mango Shake"></TreeViewItem>  
        </TreeViewItem>  
    </TreeView>  

By default, the parent node is collapsed but when you click on it, the expanded view looks as in the following. 

TreeView with items
                     Figure 1. TreeView with items 

In the previous section, we saw how to add items to a TreeView at design-time from XAML. We can add items to a TreeView from the code. 

Let's change our UI and add a TextBox and a button control to the page. The XAML code for the TextBoxand Button controls looks as in following:

  1. <TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0"   
                     Name="textBox1" VerticalAlignment="Top" Width="127" />  
    <Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top"   
                    HorizontalAlignment="Left" Width="76" Click="button1_Click">  
                Add Item  
    </Button>  

The final UI looks as in the following. On the Add Item button, the click event handler is implemented and we will add a new item to the first parent node of the TreeView.

add item
                                                                  Figure 2.

On the button click event handler, we add the content of a TextBox to the TreeViewItem using theTreeViewItem.Items.Add method. The following code adds TextBox contents to the TreeViewItem items. 

  1. private void button1_Click(object sender, RoutedEventArgs e)  
    {  
        TreeViewItem newChild = new TreeViewItem();  
        newChild.Header = textBox1.Text;  
        Parent.Items.Add(newChild);  
    }  

In the button click event handler, we add the content of a TextBox to the TreeView using theTreeViewItem.Items.Add method. 

Now if you enter text into the TextBox and click the Add Item button, it will add the contents of the TextBoxto the TreeView

Adding TreeView items dynamically
                                 Figure 3. Adding TreeView items dynamically
Note: Part 2 will update soon..

posted Aug 13, 2015 by Jdk

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


Related Articles

PART 5: Continues 

To bind an XmlDataProvider, we set the Source property inside the ItemsSource of a TreeView to the x:Keyof XmlDataProvider and the code in the code is used to filter the data. In the TreeView.ItemTempate, we use the Binding property. 

             <TreeView.ItemsSource>  
        <Binding Source="{StaticResource BooksData}"  
       XPath="*[@Category='Programming'] "/>  
    </TreeView.ItemsSource>    
    <TreeView.ItemTemplate>  
        <DataTemplate>  
            <StackPanel Orientation="Horizontal">  
                <TextBlock Text="Title: " FontWeight="Bold"/>  
                <TextBlock Foreground="Green"  >  
                    <TextBlock.Text>   
                        <Binding XPath="Title"/>  
                    </TextBlock.Text>                        
                </TextBlock>                       
           </StackPanel>  
        </DataTemplate>  
    </TreeView.ItemTemplate>  
</TreeView> 

The output of the preceding code looks as in the following.

xml data binding
                                                               Figure 11

The last data binding type we will see is how to provide data exchange between a TreeView and other controls using data binding in WPF.

We will create an application that looks as in the following. I have a TreeView with a list of colors, aTextBox and a Canvas. When we pick a color from the TreeView, the text of the TextBox and color of the Canvas changes dynamically to the color selected in the TreeView. This is possible to do all in XAMLwithout writing a single line of code in the code behind file.

code in the code
                                                           Figure 12.

The XAML code of the page looks as in the following:

             

<StackPanel Orientation="Vertical">  
    <TextBlock Margin="10,10,10,10" FontWeight="Bold">  
        Pick a color from below list  
    </TextBlock>  
    <TreeView Name="mcTreeView" Height="100" Width="100"  
             Margin="10,10,0,0" HorizontalAlignment="Left" >  
        <TreeViewItem>Orange</TreeViewItem>  
        <TreeViewItem>Green</TreeViewItem>  
        <TreeViewItem>Blue</TreeViewItem>  
        <TreeViewItem>Gray</TreeViewItem>  
        <TreeViewItem>LightGray</TreeViewItem>  
        <TreeViewItem>Red</TreeViewItem>  
    </TreeView>   
   <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left"  >  
        <TextBox.Text>  
            <Binding ElementName="mcTreeView" Path="SelectedItem.Content"/>  
        </TextBox.Text>  
    </TextBox>  
    <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left" >  
        <Canvas.Background>  
            <Binding ElementName="mcTreeView" Path="SelectedItem.Content"/>  
        </Canvas.Background>  
    </Canvas>    
</StackPanel>  

If you look at the TextBox XAML code, you will see the Binding within the TextBox.Text property that sets the binding from the TextBox to another control. Another control ID is ElementName and another control's property is Path. So in the following code, we are setting the SelectedItem.Content property of theTreeView to the TextBox.Text property.    

     <TextBox.Text>  
     <Binding ElementName="mcTreeView" Path="SelectedItem.Content"/>  
   </TextBox.Text>  

The same applies to the Canvas.Background property, where we set it to the SelectedItem.Content of theTreeView. Now, every time you select an item in the TreeView, the TextBox.Text and Canvas.Backgroundproperties are set to the selected item in the TreeView.

  1. <Canvas.Background>  
        <Binding ElementName="mcTreeView" Path="SelectedItem.Content"/>  
    </Canvas.Background>  

Summary

In this article, I exlained how to create and use a TreeView control available in WPF. We saw how to add items to a TreeView, change item properties, add images and add check boxes. In the end of this article, we saw how data binding works for a TreeView and how to bind a TreeView with data coming from objects, a database and other controls. 

READ MORE

Part 4: Continues

We will read ContactName, Address, City and Country columns in a WPF TreeView control. The finalTreeView looks as in the following: 

final TreeView

Now let's look at our XAML file. We create a resources DataTemplate type called TreeViewTemplate. A data template is used to represent data in a formatted way. The data template has two dock panels where the first panel shows the name and the second panel shows the address, city and country columns by using TextBlock controls. 

  1. <Window.Resources>  
        <DataTemplate x:Key="TreeViewTemplate">  
            <StackPanel Margin="3">  
                <DockPanel >  
                    <TextBlock FontWeight="Bold" Text="Name:"  
                      DockPanel.Dock="Left"  
                      Margin="5,0,10,0"/>  
                    <TextBlock Text="  " />  
                    <TextBlock Text="{Binding ContactName}" Foreground="Green" FontWeight="Bold" />  
                </DockPanel>  
                <DockPanel >  
                    <TextBlock FontWeight="Bold" Text="Address:" Foreground ="DarkOrange"   
                      DockPanel.Dock="Left"  
                      Margin="5,0,5,0"/>  
                    <TextBlock Text="{Binding Address}" />  
                     <TextBlock Text=", " />  
                    <TextBlock Text="{Binding City}" />  
                     <TextBlock Text=", " />  
                    <TextBlock Text="{Binding Country}" />  
                </DockPanel>  
            </StackPanel>  
        </DataTemplate>  
    </Window.Resources>   

Now in our code behind, we define the following variables. 

  1. public SqlConnection connection;   
    public SqlCommand command;   
    string sql = "SELECT ContactName, Address, City, Country FROM Customers";  
    string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";  

On the Windows_Loaded method, we use the BindData method. In the BindData method, we create a connection and a data adapter and fill in the DataSet using the SqlDataAdapter.Fill method.

  1. private void Window_Loaded(object sender, RoutedEventArgs e)  
    {  
        BindData();             
    }  
      
    private void BindData()  
    {  
        DataSet dtSet = new DataSet();  
        using (connection = new SqlConnection(connectionString))  
        {  
            command = new SqlCommand(sql, connection);                 
            SqlDataAdapter adapter = new SqlDataAdapter();             
            connection.Open();  
            adapter.SelectCommand = command;  
            adapter.Fill(dtSet, "Customers");  
            TreeView1.DataContext = dtSet;          
        }  
    }  

Now let's look at how to bind XML data to a TreeView control. The XmlDataProvider is used to bind XMLdata in WPF

  1. <XmlDataProvider x:Key="BooksData" XPath="Inventory/Books">  
        <x:XData>  
            <Inventory xmlns="">  
                <Books>  
                    <Book Category="Programming" >  
                        <Title>A Programmer's Guide to ADO.NET</Title>  
                        <Summary>Learn how to write database applications using ADO.NET and C#.  
                        </Summary>  
                        <Author>Mahesh Chand</Author>  
                        <Publisher>APress</Publisher>  
                    </Book>  
                    <Book Category="Programming" >  
                        <Title>Graphics Programming with GDI+</Title>  
                        <Summary>Learn how to write graphics applications using GDI+ and C#.  
                        </Summary>  
                        <Author>Mahesh Chand</Author>  
                        <Publisher>Addison Wesley</Publisher>  
                    </Book>  
                    <Book Category="Programming" >  
                        <Title>Visual C#</Title>  
                        <Summary>Learn how to write C# applications.  
                        </Summary>  
                        <Author>Mike Gold</Author>  
                        <Publisher>APress</Publisher>  
                    </Book>  
                    <Book Category="Programming" >  
                        <Title>Introducing Microsoft .NET</Title>  
                        <Summary>Programming .NET  
                        </Summary>  
                        <Author>Mathew Cochran</Author>  
                        <Publisher>APress</Publisher>  
                    </Book>  
                    <Book Category="Database" >  
                        <Title>DBA Express</Title>  
                        <Summary>DBA's Handbook  
                        </Summary>  
                        <Author>Mahesh Chand</Author>  
                        <Publisher>Microsoft</Publisher>  
                    </Book>  
                </Books>               
            </Inventory>  
        </x:XData>  
    </XmlDataProvider>  
READ MORE

Part 3 Continues:

We've seen many requirements where a page has two TreeView controls and the left TreeView displays a list of items. Using a button, we can use items from the left TreeView and add them to the right sideTreeView. Using the remove button we can remove items from the right side TreeView and add them back to the left side TreeView

This sample shows how to move items from one TreeView to another. The final page looks as in the following. The Add button adds the selected item to the right side TreeView and removes it from the left side TreeView. The Remove button removes the selected item from the right side TreeView and adds back to the left side TreeView.

TreeView
                                                                                    Figure 7

right side TreeView
                                                                                 Figure 8

The following XAML code generates two TreeView controls and two Button controls.

  1. <TreeView Margin="11,13,355,11" Name="LeftTreeView" />  
    <TreeView Margin="0,13,21,11" Name="RightTreeView" HorizontalAlignment="Right" Width="216" />  
    <Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top"  
            Click="AddButton_Click">Add >></Button>  
    <Button Name="RemoveButton" Margin="248,121,261,117"   
            Click="RemoveButton_Click"><< Remove</Button>  

On the Window loaded event, we create and load data items to the TreeView by setting the ItemsSourceproperty to an ArrayList

  1. private void Window_Loaded(object sender, RoutedEventArgs e)  
    {  
        // Get data from somewhere and fill in my local ArrayList  
        myDataList = LoadTreeViewData();  
        // Bind ArrayList with the TreeView  
        LeftTreeView.ItemsSource = myDataList;              
    }  
      
    /// <summary>  
    /// Generate data. This method can bring data from a database or XML file  
    /// or from a Web service or generate data dynamically  
    /// </summary>  
    /// <returns></returns>  
    private ArrayList LoadTreeViewData()  
    {  
        ArrayList itemsList = new ArrayList();  
        itemsList.Add("Coffie");  
        itemsList.Add("Tea");  
        itemsList.Add("Orange Juice");  
        itemsList.Add("Milk");  
        itemsList.Add("Mango Shake");  
        itemsList.Add("Iced Tea");  
        itemsList.Add("Soda");  
        itemsList.Add("Water");  
        return itemsList;  
    }  

In the Add button click event handler, we get the value and index of the selected item in the left sideTreeView and add that to the right side TreeView and remove that item from the ArrayList that is our data source. The ApplyBinding method simply removes the current binding of the TreeView and rebinds with the updated ArrayList.

  1. private void RemoveButton_Click(object sender, RoutedEventArgs e)  
    {  
        // Find the right item and it's value and index  
        currentItemText = RightTreeView.SelectedValue.ToString();  
        currentItemIndex = RightTreeView.SelectedIndex;  
        // Add RightTreeView item to the ArrayList  
        myDataList.Add(currentItemText);  
      
      RightTreeView.Items.RemoveAt(RightTreeView.Items.IndexOf(RightTreeView.SelectedItem));  
      
        // Refresh data binding  
        ApplyDataBinding();  

Similarly, on the Remove button click event handler, we get the selected item text and index from the right side TreeView and add that to the ArrayList and remove from the right side TreeView.

We use the Northwind.mdf database that comes with SQL Server. In our application, we will read data from the Customers table. The Customers table columns look like this. 

Customers table columns
                                           

Note:  Part 5 will update soon.  

READ MORE

Part 2 Continous:


                   <TreeViewItem Name="Child1">  

                       <TreeViewItem.Header>  

  1.             <CheckBox Name="CoffieCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="coffie.jpg" Height="30"></Image>  
                        <TextBlock Text="Coffie"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>   
        </TreeViewItem>  
        <TreeViewItem Name="Child2">  
            <TreeViewItem.Header>  
                <CheckBox Name="IcedTeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                        <Image Source="IcedTea.jpg" Height="30"></Image>  
                        <TextBlock Text="Iced Tea"></TextBlock>  
                    </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child3">  
            <TreeViewItem.Header>  
                <CheckBox Name="MangoShakeCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="MangoShake.jpg" Height="30"></Image>  
                    <TextBlock Text="Mango Shake"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child4">  
            <TreeViewItem.Header>  
                <CheckBox Name="MilkCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Milk.jpg" Height="30"></Image>  
                    <TextBlock Text="Milk"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child5">  
            <TreeViewItem.Header>  
                <CheckBox Name="TeaCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="Tea.jpg" Height="30"></Image>  
                    <TextBlock Text="Tea"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>  
        <TreeViewItem Name="Child6">  
            <TreeViewItem.Header>  
                <CheckBox Name="OrangeJuiceCheckBox">  
                    <StackPanel Orientation="Horizontal">  
                    <Image Source="OrangeJuice.jpg" Height="30"></Image>  
                    <TextBlock Text="Orange Juice"></TextBlock>  
                </StackPanel>  
                </CheckBox>  
            </TreeViewItem.Header>  
        </TreeViewItem>                  
    </TreeViewItem>  

The new TreeView looks as in the following:

TreeView with CheckBoxes
                                    Figure 6. TreeView with CheckBoxes

Before I discuss data binding in general, I must confess, the Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Maybe they have bigger plans in the future, but so far I have seen binding using dependency objects and properties, LINQDLINQWCF and ASP.NET Web Services and it all looks like a big mess. It's not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they solve this problem in the near future.

When it comes to data binding, we need to first understand the data. Here is a list of the ways data can be consumed: 

  • Objects
  • A relational database such as SQL Server
  • A XML file or
  • Other controls

The ItemsSource property of a TreeView is used to bind a collection of IEnuemerables such as anArrayList to the TreeView control. 

  1. // Bind ArrayList with the TreeView  
    LeftTreeView.ItemsSource = LoadTreeViewData();              
      
    private ArrayList LoadTreeViewData()  
    {  
        ArrayList itemsList = new ArrayList();  
        itemsList.Add("Coffie");  
        itemsList.Add("Tea");  
        itemsList.Add("Orange Juice");  
        itemsList.Add("Milk");  
        itemsList.Add("Mango Shake");  
        itemsList.Add("Iced Tea");  
        itemsList.Add("Soda");  
        itemsList.Add("Water");  
        return itemsList;  
    }  


Note:  Part 4 will update soon.  

READ MORE

REF: Before proceed please read Treeview in XAML first Part then continue.

We can use TreeView.Items.Remove or the TreeView.Items.RemoveAt method to delete an item from the collection of items in the TreeView. The RemoveAt method takes the index of the item in the collection. 

Now, we modify our application and add a new button called Delete Item. The XAML code for this button looks as in the following:

 <Button Height="23" Margin="226,14,124,0" Name="DeleteButton"   
 VerticalAlignment="Top" Click="DeleteButton_Click">  
 Delete Item</Button>​

The button click event handler looks as in the following. On this button click, we find the index of the selected item and use the TreeView.Items.RemoveAt method as in the following. 

private void DeleteButton_Click(object sender, RoutedEventArgs e)  
{  
        TreeView1.Items.RemoveAt  
       (TreeView1.Items.IndexOf(TreeView1.SelectedItem));                    
}  ​ 

The preceding code removes root items from the TreeView, not the sub-items. To remove sub items, we need to find the selected item and then we need to use the TreeViewItem.Items.RemoveAt method.

TreeView control is placed inside a StackPanel that contains a ScrollViewer control so when the width or height of the panel is more than the visible area, the scroll viewer becomes active and provides horizontal and vertical scrolling functionality. 

To style a TreeView, we can use individual TreeViewItems and set their properties. Alternatively, we can use System.Resources and set Style property. The following code snippet sets TreeViewItem foreground, font size and font weight properties. 

  1. <Window.Resources>  
        <Style TargetType="{x:Type TreeViewItem}">  
            <Setter Property="Foreground" Value="Blue"/>              
            <Setter Property="FontSize" Value="12"/>  
            <Setter Property="FontWeight" Value="Bold" />  
        </Style>  
    </Window.Resources> 


Formatted TreeView
                                             Figure 4. 

We can put any controls inside a TreeViewItem such as an image or text. To display an image side by side text, I simply put an Image and TextBlock control within a StackPanel. The Image.Source property takes the name of the image you would like to display in the Image control and TextBlock.Text property takes a string that you would like to display in the TextBlock.

The following code snippet adds image and text to a TreeViewItem. The key here is to add an image and text to the header of TreeViewItems

  1. <TreeViewItem Name="Child1">  
        <TreeViewItem.Header>  
            <StackPanel Orientation="Horizontal">  
                <Image Source="coffie.jpg" Height="30"></Image>  
                <TextBlock Text="Coffie"></TextBlock>  
            </StackPanel>  
        </TreeViewItem.Header>   
    </TreeViewItem>    

After changing my code for all 5 TreeViewItems

TreeViewItems with Image and text
                              Figure 5. 

If you put a CheckBox control inside TreeViewItems, you generate a TreeView control with checkboxes in it. The CheckBox can host controls within it as well. For instance, we can put an image and text block as content of a CheckBox.

The following code snippet adds a CheckBox with an image and text to a TreeViewItem.

  1. <TreeViewItem Name="Child1">  
        <TreeViewItem.Header>  
            <CheckBox Name="CoffieCheckBox">  
                <StackPanel Orientation="Horizontal">  
                <Image Source="coffie.jpg" Height="30"></Image>  
                <TextBlock Text="Coffie"></TextBlock>  
            </StackPanel>  
            </CheckBox>  
        </TreeViewItem.Header>   
    </TreeViewItem>   

I change the code of TreeViewItems and add the following CheckBoxes to the items. As you may see, I have set the name of the CheckBoxes using the Name property. If you need to access these CheckBoxes, you may access them in the code using their Name property. 

​PART 3: will update soon :) 

READ MORE

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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  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>   
  11.               
  12.             <TextBlock FontSize="12" FontWeight="Regular">  
  13.                 This is a group box control content.                  
  14.             </TextBlock>               
  15.            
  16.         </GroupBox>  
  17.   
  18.     </Grid>  
  19. </Window>  

The output looks like this.

READ MORE

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"  
   Name="MonthlyCalendar"   
   SelectedDatesChanged="MonthlyCalendar_SelectedDatesChanged"  
   DisplayDateChanged="MonthlyCalendar_DisplayDateChanged"  
   DisplayModeChanged="MonthlyCalendar_DisplayModeChanged"  
   HorizontalAlignment="Left"  
   VerticalAlignment="Top"  
   Margin="10,10,0,0">   
</Calendar>   

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"  
   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 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.

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

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. 

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

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.

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

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;    
    LayoutRoot.Children.Add(MonthlyCalendar);  
}  

Listing 6

Summary


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.

READ MORE
...