top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

How to use XAML slider in Windows Phone Environment Part 2?

+4 votes
66 views

We have already learned the basic concepts of XAML Slider. If you haven't then please refer to my previous article http://tech.queryhome.com/91876/how-to-use-xaml-slider-in-windows-phone-environment-part-1

The code that generates Figure 3 is listed in Listing 2

<Canvas x:Name="LayoutRoot" Background="LightGray" >
    <!-- Create an Ellipse -->  
    <Ellipse x:Name="mcCircle" Width="200" Height="200" 
             Canvas.Left="60" Canvas.Top="20" 
             Fill="Gray" Stroke="Black" StrokeThickness="2">              
    </Ellipse>        
    <!-- Create Slider controls -->  
    <Slider x:Name="RedSlider" Width="300" Height="20"  
            Background="Red" Maximum="255" Minimum="0"                 
            Canvas.Left="30" Canvas.Top="240"  
            ValueChanged="RedSlider_ValueChanged"/>  
    <Slider x:Name="GreenSlider" Width="300" Height="20"  
            Background="Green" Maximum="255" Minimum="0"                   
            Canvas.Left="30" Canvas.Top="270"  
            ValueChanged="GreenSlider_ValueChanged"/>  
    <Slider x:Name="BlueSlider" Width="300" Height="20"  
            Background="Blue" Maximum="255" Minimum="0"                  
            Canvas.Left="30" Canvas.Top="300"  
            ValueChanged="BlueSlider_ValueChanged"/>  
</Canvas> 

Listing 2

Now, on the ValueChanged event of the slider controls, we write the code listed in Listing 3. In this code, we simply create a Color from the values of the slider controls and create a brush with this color and fill in the circle.

private void RedSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)  
{  
    UpdateCircleWithColors();  
}  
  
private void GreenSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)  
{  
    UpdateCircleWithColors();  
}  
  
private void BlueSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)  
{  
    UpdateCircleWithColors();  
}  
  
private void UpdateCircleWithColors()  
{  
    Color clr = Color.FromArgb(255, Convert.ToByte(RedSlider.Value),  
        Convert.ToByte(GreenSlider.Value), Convert.ToByte(BlueSlider.Value));  
    mcCircle.Fill = new SolidColorBrush(clr);  
}   

Listing 3

Now if you run the application and change the slider values, you will see the fill color of the circle change accordingly. See Figure 4.

color of circle
Figure 4

posted Jun 30, 2015 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button


Related Articles

The XAML Slider element represents a slider. This article shows you how to use a Slider in Windows Phone.

Slider Control

The Slider element in XAML represents a WPF Slider control.          

      <Slider></Slider>  

Slider Control Properties

The Width and Height properties represent the width and the height of the control. The x:Name property represents the name of the control and is a unique identifier of the control. The Background property is used to set the background color of the control. The Minimum and Maximum properties represent the minimum and maximum values of the slider range. 

The code snippet in Listing 1 creates a Slider control and sets its name, height, width, background, maximum and minimum properties.

 <Slider x:Name="mcSlider" Width="300" Height="20"  

      Background="Gray" Maximum="100" Minimum="0">              

</Slider>  

 

Listing 1

The code snippet in Listing 1 generates output that looks as in Figure 1
output
Figure 1

The IsFocused property indicates whether the slider control has the focus and the IsDirectionReversedproperty represents the direction of the increasing value. By default, the slider control sits on the UI in a horizontal direction. Using the Orientation property, a slider control can be placed vertically.

The code snippet in Listing 2 sets the orientation of a slider control to vertical. 
 

  1. <Slider x:Name="mcSlider" Width="30" Height="300"  
  2. Background="Gray" Maximum="100" Minimum="0" Orientation="Vertical" >  
  3. </Slider>  

Listing 2

The code snippet in Listing 2 generates output that looks as in Figure 2

                                          generates output
                                                Figure 2

The Application

Now we will create a real-world application that will use Slider control values to create a color from the three values Red, Green and Blue respectively. From these three values, we will create a color and fill an ellipse with that color.

First we create a UI page with one circle and three slider controls that looks as in Figure 3

slider controls that looks
Figure 3

Continue in How to use XAML slider in Windows Phone Environment Part 2 Please refer this link: http://tech.queryhome.com/92358/how-to-use-xaml-slider-in-windows-phone-environment-part-2?

READ MORE

The following code snippet adds blackout dates to a Calendar. 

<Calendar.BlackoutDates>  
   <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"/>  
</Calendar.BlackoutDates>  

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"   
   SelectionMode="MultipleRange"   
   DisplayDate="3/1/2010"  
   DisplayDateStart="3/1/2010"  
   DisplayDateEnd="3/31/2010"  
/>  

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"   
   SelectionMode="MultipleRange"   
   DisplayDate="3/5/2010"  
   DisplayDateStart="3/1/2010"  
   DisplayDateEnd="3/31/2010"  
   FirstDayOfWeek="Tuesday"  
   IsTodayHighlighted="True"   
   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"   
    SelectionMode="MultipleRange"    
    DisplayDate="3/5/2010"  
    DisplayDateStart="3/1/2010"  
    DisplayDateEnd="3/31/2010"  
    FirstDayOfWeek="Tuesday"  
    IsTodayHighlighted="True"   
    xmlns:sys="clr-namespace:System;assembly=mscorlib" Margin="15,39,88,19">    
    <Calendar.SelectedDates>  
        <sys:DateTime>3/5/2010</sys:DateTime>  
        <sys:DateTime>3/15/2010</sys:DateTime>  
        <sys:DateTime>3/25/2010</sys:DateTime>  
     </Calendar.SelectedDates>    
</Calendar>  

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

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

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

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. 
 

CalendarSelectionModeDescription
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>  

BlackoutDates

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

READ MORE

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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...