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 PolyQuadraticBezierSegment ?

+4 votes
95 views

The PolyQuadraticBezierSegment object in WPF represents one or more quadratic Bezier curves. The Points property represents all the points for multiple Bezier curves. The element PolyQuadraticBezierSegment represents the PolyQuadraticBezierSegment object in XAML.

 

The following XAML code snippet sets the Points property of the PolyQuadraticBezierSegment. 

 

<PolyQuadraticBezierSegment Points="0,0 50,0 100,100 100,0 150,0 200,100" />         

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

 

<Path Stroke="Blue" StrokeThickness="2" >

    <Path.Data>

        <PathGeometry>

            <PathGeometry.Figures>

                <PathFigureCollection>

                    <PathFigure StartPoint="10,100">

                        <PathFigure.Segments>

                            <PathSegmentCollection>

                                <PolyQuadraticBezierSegment Points="0,0 50,0 100,100 100,0 150,0 200,100" /> 

                            </PathSegmentCollection>

                        </PathFigure.Segments>

                    </PathFigure>

                </PathFigureCollection>

            </PathGeometry.Figures>

        </PathGeometry>

    </Path.Data>

</Path>

 

The output looks as in Figure 1. 

 

PolyQuadraticBezierSegment1.jpg

Figure 1

 

We can paint a Bezier curve by simply painting the path using the Fill method. The following code snippet has been changed from the previous code and fills a path.  

<Path StrokeThickness="2" Fill="Yellow" >

The new output looks as in Figure 2. 

 

PolyQuadraticBezierSegment2.jpg

 

Figure 2

The following code snippet creates a poly quadratic Bezier segment dynamically that looks as in Figure 2. 

private void CreatePolyQuadraticBezierSegment()

{

    PathFigure pthFigure = new PathFigure();

    pthFigure.StartPoint = new Point(10, 100);

    PolyQuadraticBezierSegment pqbzSeg = new PolyQuadraticBezierSegment();

    pqbzSeg.Points.Add(new Point(0, 0));

    pqbzSeg.Points.Add(new Point(50, 0));

    pqbzSeg.Points.Add(new Point(100, 100));

    pqbzSeg.Points.Add(new Point(100, 0));

    pqbzSeg.Points.Add(new Point(150, 0));

    pqbzSeg.Points.Add(new Point(200, 100));

    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();

    myPathSegmentCollection.Add(pqbzSeg);

    pthFigure.Segments = myPathSegmentCollection;

    PathFigureCollection pthFigureCollection = new PathFigureCollection();

    pthFigureCollection.Add(pthFigure);

    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);

    LayoutRoot.Children.Add(arcPath);

}

posted Dec 22, 2015 by Jdk

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


Related Articles

XAML RepeatButton in WPF

XAML RepeatButton represents a set of repeat buttons. This article shows how to use a RepeatButton control in WPF using XAML and C#. 

Creating a RepeatButton

The RepeatButton XAML element represents a WPF RepeatButton control. 

  1. <Button/>  

The Width and Height attributes represent the width and the height of a RepeatButton. The Content property sets the text of the button. 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 Button control and sets its name, height, width and content. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
</RepeatButton>  

Listing 1

The default property of a button is Content. The code snippet in Listing 2 creates the same button as created by Listing 1.

<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30">  
   Grow  
</RepeatButton>  

Listing 2

The output looks as in Figure 1



Figure 1

Delay and Interval

The Delay and Interval properties make a RepeatButton different from a normal button. 

RepeatButton is a button that fires Click events repeatedly when it is pressed and held. The rate and aspects of repeating are determined by the Delay and Interval properties that the control exposes.

The code snippet in Listing 3 sets the Delay and Interval properties. 


<RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
   HorizontalAlignment="Left"   
   Name="GrowButton" Width="80" Height="30"   
   Delay="500" Interval="100" >  
   Grow  
</RepeatButton>  

Listing 3

Adding a Button Click Event Handler

The Click attribute of a RepeatButton element adds the click event handler and it keeps firing the event for the given Interval and delay values. The code in Listing 4 adds the click event handler for a Button. 

<Button x:Name="DrawCircleButton" Height="40" Width="120"   
        Canvas.Left="10" Canvas.Top="10"   
        Content="Draw Circle"  
        VerticalAlignment="Top"   
        HorizontalAlignment="Left">  
Click="DrawCircleButton_Click"  
</Button>  

Listing 4

The code for the click event handler looks as in following. 

  1. private void GrowButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3. }  

Okay, now let's write a useful application. 

We will build an application with the two buttons Grow and Shrink and a rectangle. The application looks as in Figure 2.

When you click and continue pressing the Grow button, the width of the rectangle will continue to grow and when you click on the Shrink button, the width of the rectangle will shrink continuously. 



Figure 2

The final XAML code is listed in Listing 5

<Window x:Class="RepeatButtonSample.Window1"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    Title="Window1" Height="300" Width="300">  
      
    <Grid Name="LayoutRoot">  
        <RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="GrowButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="GrowButton_Click">  
            Grow  
        </RepeatButton>  
        <RepeatButton Margin="100,10,0,0" VerticalAlignment="Top"   
                      HorizontalAlignment="Left"                         
                      Name="ShrinkButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
                      Click="ShrinkButton_Click">  
            Shrink  
        </RepeatButton>  
          
        <Rectangle Name="Rect" Height="100" Width="100" Fill="Orange"/>  
  
    </Grid>  
</Window>  

Listing 5

Listing 6
 is the click event handlers for the buttons that change the width of the rectangle.

private void GrowButton_Click(object sender, RoutedEventArgs e)  
{  
    Rect.Width += 10;  
}  
  
private void ShrinkButton_Click(object sender, RoutedEventArgs e)  
{  
   

Listing 6

READ MORE

In this article you will learn how to create and use a CustomResource in XAML.

 

  1. Open a new Visual C# windows project.
     
  2. Add a new class named say CustomResourceTest.cs in the project folder.

    CustomResourceTest.cs
     
  3. Derive this class from CustomXamlResourceLoader Class(Case sensitive) like below:

    CustomXamlResourceLoader Class
     
  4. You will get a Namespace not found error. Resolve it by using Windows.UI.Xaml.Resources Namespace.

    Windows.UI.Xaml.Resources
     
  5. Override the GetResource Member of the parent class as below. Use the intellisense to select the member.

    getresource

    getresource1
     
  6. Replace the Code inside the GetResource Method as: (this is just a simple example). We are returning a text. We plan to show this text inside a TextBlock’s Text Property.

    TextBlock
     
  7. Inside the MainPage.cs . Add the following line of code inside the MainPage Constructor to reference the CustomResouceTest.cs Class from the Page’s XAML.

    MainPage

    Correct the NameSpace not found error by resolving it.
     
  8. Now go to the MainPage.xaml Page and Add a TextBlock as follows. Notice the Text property of the TextBlock.

    MainPage.xaml
     
  9. This results in the following output when you save, build and run the project.

    run
     
  10. What is happening here?
     
    • We created a CustomResourceClass where we inherited the Class called CustomXamlResourceLoader.
    • We override the GetResourceProperty. Don’t focus on the parameters of this method for now.
    • We replaced the code inside this method by simply returning a text.
    • To access this CustomResource from XAML we have to define the CustomXamlResourceLoader. Current property to the new instance of the Class we created. We have to do this inside the Constructor of the Codebehind page where we want to use the CustomResource.
    • We then simply assigned the value of the Text property of the textblock to the CustomResource as seen on Step 8.

Example 2:

  1. Now we will try a different example where we want to display the Text of the TextBlock based on the value we pass on. Change the text of the Mainpage.xaml as:

    Mainpage.xaml 2
     
  2. The 'sayHello' string is passed as a string to the CusomResourceTest.cs class as ResourceID parameter of the overridden class. This will be more clear as you see in the next step.
     
  3. In the CustomResourceTest.cs class , change the code as follows:

    CustomResourceTest.cs2
     
  4. The thing to understand is how we pass the ResourceID from the Text Property of the TextBlock. It is passed as the resourceID parameter. So, based on the ResourceID, we return the appropriate text we want to display on the output screen.
     
  5. So now we get output as.
  6. If we change the text property as sayByeBye.

    sayByeBye
     
  7. We get the following output:
     
READ MORE

We're going to discuss about Automatic Type converters in XAML.

Whenever you make some control in XAML you set its properties. For example in following screen shot we are making a button in XAML and setting its properties like:

  • Name
  • Horizontal Alignment
  • Margin
  • Background
  • Vertical Alignment
  • Horizontal Alignment
  • Background Color etc , you are shown a list of given option through Intellisense like below:


     

So you have limited options as shown in above screenshot. you've to select 1 position from 4 given options . These options are infect enums.

    have you ever noticed that when you type in for setting the properties like ,

    Now I'm going to show you the alternate way to set properties using C# syntax. To make a button from C# write following code in Page Load Event in program.

    When you make a control from C# code. You've to set all of its properties in code. In this case we've set its

    • HorizontalAlignment 
    • Background properties

    You selected the background color and Horizontal Alignment from a strongly typed enumeration for the button. So the question is ! How these properties are mapped to strongly typed enumeration, when you type a string which is "left" in the case of alignment property and "Red" in case of color selection.

    Answer is ! XAML parser does this job.

    XAML parser convert string value into a strongly typed version of that value. So when you set the properties like < horizontalAllignment = "Left" > , the string "Left" will be mapped to the strongly typed enum by the XAML parser.

    READ MORE

    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.

     

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

     

    AnimatedBanImg2.jpg

    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.

    <TextBlock.Triggers>

          <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                <BeginStoryboard>

                      <Storyboard>

                                             

                      </Storyboard>

                </BeginStoryboard>

          </EventTrigger>

    </TextBlock.Triggers>

    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.

    <DoubleAnimation

          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.

    <ColorAnimation

    Storyboard.TargetName="SB"

    Storyboard.TargetProperty="Color"

    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.

    <DoubleAnimation

    Storyboard.TargetName="MyRT"

          Storyboard.TargetProperty="(RotateTransform.Angle)"

          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:

    <Window

          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

          x:Class="AnimatedBanner.Window1"

          x:Name="Window"

          Title="Window1"

          Width="396" Height="492"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d" Foreground="#FFF15151" SnapsToDevicePixels="True" >

     

          <Grid x:Name="LayoutRoot">

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

                      <Rectangle.Fill>

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

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

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

                            </LinearGradientBrush>

                      </Rectangle.Fill>            

                </Rectangle>

               

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

                            </LinearGradientBrush>

                      </TextBlock.Background>

                      <TextBlock.Triggers>

                            <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                                  <BeginStoryboard>

                                        <Storyboard>

                                              <DoubleAnimation

                                                    Storyboard.TargetName="TB"

                                                    Storyboard.TargetProperty="Opacity"

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

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

                                        </Storyboard>

                                  </BeginStoryboard>

                            </EventTrigger>

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

                            </LinearGradientBrush>

                      </TextBlock.Background>

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

                      <TextBlock.Triggers>

                            <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                                  <BeginStoryboard>

                                        <Storyboard/>

                                  </BeginStoryboard>

                            </EventTrigger>

                      </TextBlock.Triggers>

                      </TextBlock>

         

               

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

                <TextBlock

                  x:Name="TB4"

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

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

                  <TextBlock.Foreground>

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

                  </TextBlock.Foreground>

     

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

                  <TextBlock.Triggers>

                    <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                      <BeginStoryboard>

                        <Storyboard>

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

                            to draw the text -->

                          <ColorAnimation

                            Storyboard.TargetName="SB"

                            Storyboard.TargetProperty="Color"

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

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

                        </Storyboard>

                      </BeginStoryboard>

                    </EventTrigger>

                  </TextBlock.Triggers>

                </TextBlock>

     

     

                <!-- Text Rotation Sample -->

                <TextBlock

                  x:Name="TB5"

                  Margin="97,0,183,41"

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

                      <BeginStoryboard>

                        <Storyboard>

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

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

                          <DoubleAnimation

                            Storyboard.TargetName="MyRT"

                            Storyboard.TargetProperty="(RotateTransform.Angle)"

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

                            RepeatBehavior="Forever" />

                        </Storyboard>

                      </BeginStoryboard>

                    </EventTrigger>

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

               

                <!-- Author TextBlok -->

         

          </Grid>

    </Window>

    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

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