top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Create an Animation of a Ball Being Thrown in silverLight?

+4 votes
576 views

This tutorial shows you how to create an animation of a ball being thrown across the screen, landing and bouncing.

Step by Step Tutorial

A brief description of how to use the article or code. The class names, the methods and properties, any tric

  1. Create a new project in Expression Blend. 
     
  2. Draw an ellipse and name the ellipse "ball" 

    image001.jpg
     
  3. The key to creating a bounce effect is to realize that in physics the vertical motion of a ball in motion is completely independent of the horizontal motion. What we're going to do is create two separate story boards for each of these independent motions and then we're going to go into the XAML and combine them into one storyboard. 
     
  4. Create a new storyboard called "Bounce" 
     
  5. Record a keyframe at time 0 for the ball to capture the current position. Then drag the yellow timeline bar to the 1 second position. 

    image002.jpg

 

  1. Now drag the red ball directly up. And record a key frame. At the one second point. Hit play and you should see the ball move directly up at a smooth rate and then stop. 

    image003.jpg

 

  1. Now let's add some gravity. Click on the second keyframe bubble of the storyboard. Set the easing as shown below. This will make the motion slow down as the ball gets to the top of its motion. Confirm this by playing the storyboard. Once you've confirmed this close out the storyboard. 

    image004.jpg

 

  1. Create a storyboard called Horizontal. Create a keyframe at 0 seconds, and then set the timeline to 2 seconds. Drag the ball horizontally to the right and create a keyframe at the 2 second point. Close out the storyboard. 

    image005.jpg

 

  1. Now let's look at the XAML for the Bounce storyboard. Unless you drug the ball perfectly vertically you'll have two sections in the storyboard, one for animating the x direction and one for animation the y direction. You can tell which is which by looking for the line that ends TranslateTransform.Y or TranslateTransform.X. Delete the section that handles the X motion. 
     
  2. Now let's make the ball return to it's starting point. 

    Here's the XAML before hand:

    image006.jpg

    Notice it's moving the ball from a position of 0 to a position of -206 in 1 second. ControlPoint1's value of 0,1 indicates we are going to start at full speed and reach minimum speed at the end of the motion. To make the ball return back down we'll copy the second keyframe, change to time of the key to 2 seconds, change the destination of the animation to 0, and we'll reverse the sense of the easing defined by ControlPoint2. The results are as follows:

    image007.jpg

    Select the bounce storyboard and hit play. You should see the ball go up and down as if it's been thrown up and down.
     
  3. Now let's add the X motion. Take a look at second storyboard we made earlier called horizontal. Copy the DoubleAnimationUsingKeyFrames section that ends TranslateTransform.X and paste it into the Bounce storyboard. Open the bounce storyboard from the design review and hit play. You should see the ball move in a nice smooth arc as if it has been thrown. 

    image008.jpg

 

 

  1. To add a bounce we simply follow the same pattern and add additional key frames. To the DoubleAnimationUsingKeyFrames section that ends TranslateTransform.X add one more keyframe at 3 seconds by adding the following XAML: 

    <SplineDoubleKeyFrame KeyTime="00:00:03" Value="320"/>

    This XAML sets the position that the ball will move to at the end of the third second to 320 which is 22 to the right of where it was in at the end of the previous keyframe. For the vertical portion of the bounce copy the last two keyframes of the DoubleAnimationUsingKeyFrames section that ends TranslateTransform.Y. Set the keyframe time for the peak of the bounce to 2.5 seconds and a height of -20. Have the bounce return to 0 at 3 seconds. This results in the addition of the following XAML:

    <SplineDoubleKeyFrame KeyTime="00:00:02.5" Value="-20">
    <SplineDoubleKeyFrame.KeySpline>
    <KeySpline ControlPoint1="0,1" ControlPoint2="1,1"/>
    </SplineDoubleKeyFrame.KeySpline>
    </SplineDoubleKeyFrame>
    <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0">
    <SplineDoubleKeyFrame.KeySpline>
    <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
    </SplineDoubleKeyFrame.KeySpline>
     
  2. To make the throw occur over and over add a RepeatBehavior to the Storyboard. 

    <Storyboard RepeatBehavior="Forever" x:Name="Bounce">
     
  3. Finally let's add code to start the throw on the load of the page 

    public Page() 

    // Required to initialize variables 
    InitializeComponent(); 
    Loaded += new RoutedEventHandler(PageLoaded); 


    void PageLoaded(object sender, RoutedEventArgs e) 

    Bounce.Begin(); 
    }

     
  4. That's it. Hit F5 and you should see the ball being thrown and bouncing.
posted Dec 14, 2015 by Jdk

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


Related Articles

Visual Studio 2008 and .Net framework 3.5 provide us several new features not found in the precedent version. The WPF, the XAML and Silverlight are among the new features introduced in a WPF context. They contribute to the amelioration of the application ergonomic side by introducing something new like 2D/3D animations. For instance, Visual studio 2008 and Silverlight products must be installed before starting with animations. For me, this is my first experience within VS 2008, XAML, WPF and Silverlight.  

As you will see, a given animation can target a given control such as a rectangle, a grid or an even a button witches are called canvas. The animation by definition is this context is the given control property or properties changement from given statue to another via an interpolation that could be monitored by the developer via code xaml or via the page code behind. I mean C # code. It is similar phenomenon when comparing with the flash animations, if you have already dealt with flash projects especially the movement and the form interpolations. There are three main animations in addition to a set of witches those provided by the System.Window.Media.Animation namespace,  all could be used in order to achieve a particular goal, but in this article and the ones witches will follow this one,  we'll concentrate on the three kind of animations, namely the Double animation, the Color animation and the point animation, moreover, the .Net frameworks provides a set of base classes such DoubleAnimationBase, ColorAnimationBase and PointAnimationBase to customize your code in addition to other classes like Aniamtable and interfaces such as IAnimatable. All of them are provided to perform customized animations within your WPF application.

In this article, I will give a trick of how to deal with ColorAnimation class within VS2008 and Silverlight context using both xaml and C# 4.0, afterward, and in the two subsequent articles, we'll focus on the DoubleAnimation and PointAnimation:

The Color animation:

In this example we will define a rectangle that changes color from yellow to red if the mouse enters the given object boundaries and then returns to the first color if the mouse leaves the rectangle.

XAML code:

Create a new WPF application by open New>Project>WPFApplication then name your application my first WPF application. Copy and paste this under code to the xaml zone.

<Window x:Class="myWpfApplication.Window1"

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

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

    Title="Window1" Height="400" Width="400" Loaded="Window_Loaded">

<!—The rectangle extends the Animatable class so it can be target of an

 Animation therefore a chose it -->

    <Rectangle Width="250" Height="250" ToolTip="This is myRectangle" Name="myRectangle"Visibility="Visible" Fill="Yellow">

        <Rectangle.Triggers>

             <!—The mouse enter event is the one that triggers the animation -->

            <EventTrigger RoutedEvent="Rectangle.MouseEnter">

            <!—The Storyboard is a sort of aniamtion container-->

                <BeginStoryboard>

                    <Storyboard>

                    <!—The color, the duration, and the targeted property that will

                       Be subject of the aniamtion, all parameters are set within the animation tag  -->

                        <ColorAnimation Storyboard.TargetName="myRectangle"

                                         Storyboard.TargetProperty="(Fill).(Color)"

                                         Duration="00:00:08"

                                         From="Yellow" To="Red"                                  

                                         />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

            <!—As you see, you can implement more that one animation for the same

               Object at the same time -->

          <EventTrigger RoutedEvent="Rectangle.MouseLeave">

                <BeginStoryboard>

                    <Storyboard>

                        <ColorAnimation Storyboard.TargetName="myRectangle"Storyboard.TargetProperty="(Fill).(Color)"

                                        Duration="00:00:08" From="Red" To="Yellow"

                                        />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

        </Rectangle.Triggers>

    </Rectangle>

</Window>

C# code:

Also this task could be performed using the form code behind, I mean C#, to do so open a new window drag and drop a new rectangle.

Figure 1

Then right click on it and choose the properties menu.

Figure 2

Afterward, select the properties menu item and set it property name to "myRectangle" width to "250" and it height to "250".

Then implement the code as bellow, but don't forget to append System.Windows.Media.Animation namespace to the project:

//It is used to fill myRectangle object

SolidColorBrush TransformBrush;

//This animation is for changing the color

ColorAnimation oColorAnimation;

private void Window_Loaded(object sender, RoutedEventArgs e)

{

//First we set the color to yellow

TransformBrush = new SolidColorBrush(Colors.Yellow);

//Fill the rectangle using the TransformBrush

myRectangle.Fill = TransformBrush;

//Those two lines are responsibles for triggering events MouseEnter and MouseLeave

myRectangle.MouseEnter+=new MouseEventHandler(myRectangle_MouseEnter);

myRectangle.MouseLeave+=new MouseEventHandler(myRectangle_MouseLeave);

}

private void myRectangle_MouseEnter(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

 

//The initial brush state

oColorAnimation.From = Colors.Yellow;

//The final brush state

oColorAnimation.To = Colors.Red;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

 

}

private void myRectangle_MouseLeave(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

//The initial brush state

oColorAnimation.From = Colors.Red;

//The final brush state

oColorAnimation.To = Colors.Yellow;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

 

READ MORE

Introduction

If you are developing a Silverlight Application, and you need to pass some parameters inside – for example a key and value pair then we can pass the key value pair from the aspx page itself. We will see how we can do this in Silverlight.

Create a Silverlight Project



Figure 1.1 Creating Silverlight Project

Adding parameters

Open the "InitializingParametersTestPage.aspx" and find the tag tag  <asp:Silverlight  add an attribute InitParameters
Enter the following code to the tag

InitParameters="Key1=Value1,Key2=Value2"

Defining the Parameters

In App.xaml.cs add an object of IDictionary<string,string> as follows

public IDictionary<string, string> AppParams;
In Application_Startup event initialize the parameters as follows
private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppParams = e.InitParams;
            this.RootVisual = new Page();
        }

Using Parameters

In Page.xaml add ListBoxes to show the parameter values
Xaml Code

<UserControl x:Class="InitializingParameters.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="#FFB7C2E5">
                <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="0.472*"/>
                                <ColumnDefinition Width="0.025*"/>
                                <ColumnDefinition Width="0.502*"/>
                </Grid.ColumnDefinitions>
        <ListBox x:Name="myKeysList"/>
        <ListBox x:Name="myValuesList" Grid.Column="2"/>
    </Grid>
</UserControl>

In code behind of the Page.xaml.cs add the following code to bind the parameters

namespace InitializingParameters
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            App myApp = App.Current as App;

            foreach (string item in myApp.AppParams.Keys)
            {
                myKeysList.Items.Add(item);
            }
            foreach (string item1 in myApp.AppParams.Values)
            {
                myValuesList.Items.Add(item1);
            }
        }
    }
}

Runnning the Application

When you run the application the list will carry the key and value pairs.



Figure 1.2 Displaying Key Value pair

READ MORE

In this article we will explore on Pie Chart in Silverlight 3. Pie Chart comes with Silverlight 3 Toolkit.

Crating Silverlight Project

Fire up Expression Blend 3 and create a Silverlight Application. Name it as PieChartInSL3.

PieChartImg1.gif

 

Go ahead and add a Pie Series into your application.

You can find it in Asset Library.

PieChartImg2.gif

By adding a Pie Series, you just added an Assembly System.Windows.Controls.DataVisualization.

And Blend automatically refers to the Namespace.

If you see the xaml code behind you will find the following:

xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

Now we will add some data into it.

Create a class called Appointment and add the following code into it.

public class Appointment

    {

        public int Id { get; set; }

        public string AppName { get; set; }

        public string AppointmentDetails { get; set; }

        public int Duration { get; set; }

 

        public Appointment()

        {

        }

 

        public Appointment(int id, string appName, string appointmentDetails, int duration)

        {

            Id = id;

            AppName = appName;

            AppointmentDetails = appointmentDetails;

            Duration = duration;

        }

 

    }

Pie Series takes Key Value pair as it's data. So we will create a class named AppointmentHelper which will convert a Dictionary to Key Value Pair.

 

public static Dictionary<String, int> GetTimeDistribution(this List<Appointment> appts)

        {

            Dictionary<String, int> myTimeDistribution = new Dictionary<string, int>();

 

            var appointments = (from time in appts

                                select time.AppName).Distinct();

 

            foreach (var app in appointments)

            {

                var time = (from pjts in appts

                            where pjts.AppName == app

                            select pjts.Duration).Sum();

 

                myTimeDistribution.Add(app, time);

 

            }

            return myTimeDistribution;

        }

 

Now we will add values.

List<Appointment> appointments;

 

                                public MainPage()

                                {

                                                InitializeComponent();

                CreateTimeLists();

                                }

 

        private List<AppointmentDTO> CreateTimeLists()

        {

            appointments = new List<Appointment>

            {

                new Appointment { Id=1, AppName="Meeting", AppointmentDetails="Video COnference", Duration=30},

                new Appointment { Id=1, AppName="Call", AppointmentDetails="Audio COnference", Duration=90},

                new Appointment { Id=1, AppName="Session", AppointmentDetails="Session for Silverlight", Duration=120}

            };

            return appointments;

        }

Now we will bind our data to Pie Series.

<chartingToolkit:Chart x:Name="TypicalChart" Title="Typical Pie Chart">

            <chartingToolkit:Chart.Series>

                <chartingToolkit:PieSeries Margin="0,0,20,20" d:LayoutOverrides="Width, Height" Title="Pie Chart Sample"IndependentValueBinding="{Binding Path=Key}"

                    DependentValueBinding="{Binding Path=Value}"/>

            </chartingToolkit:Chart.Series>

        </chartingToolkit:Chart>

As you see from the above code I have added two properties as IndependentValueBinding and DependentValueBinding. We need to give the Binding Path to respective key and value.

Now Type cast the chart to Pie Series and assign the ItemSource property.

private void UserControl_Loaded(object sender, RoutedEventArgs e)

        {

            ((PieSeries)TypicalChart.Series[0]).ItemsSource = appointments.GetTimeDistribution();

        }

 

Now go ahead run the application to see the Pie Chart.

PieChartImg3.gif

That's it you have successfully used Pie Series in Silverlight 3.

READ MORE

This article demonstrates how to create and use an image brush in Silverlight using XAML and C#.

Image Brush

An image brush paints an area with an image. The ImageSource property represents the image to be used during the painting by an image brush. The ImageBrush object represents an image brush. 

Creating an Image Brush

The ImageBrush element in XAML creates an image brush. The ImageSource property of the ImageBrush represents the image used in the painting process.

The following code snippet creates an image brush and sets the ImageSource property to an image.

<ImageBrush ImageSource="dock.jpg" />

We can fill a shape with an image brush by setting a shape's Fill property to the image brush. The code snippet in Listing 1 creates a rectangle shape sets the Fill property to an ImageBrush.

<Rectangle

    Width="200"

    Height="100"

    Stroke="Black"

    StrokeThickness="4">

    <Rectangle.Fill>

        <ImageBrush ImageSource="dock.jpg" />

    </Rectangle.Fill>

</Rectangle>

Listing 1

The output looks like Figure 1.

 

ImageBrush1.gif

Figure 1

The CreateAnImageBrush method listed in Listing 2 draws same rectangle with an image brush in Figure 1 dynamically.

/// <summary>

/// Fills a rectangle with an ImageBrush

/// </summary>

public void CreateAnImageBrush()

{

    // Create a Rectangle

    Rectangle blueRectangle = new Rectangle();

    blueRectangle.Height = 100;

    blueRectangle.Width = 200;

 

    // Create an ImageBrush

    ImageBrush imgBrush = new ImageBrush();

 

    imgBrush.ImageSource =

        new BitmapImage(new Uri(@"Dock.jpg", UriKind.Relative));

 

    // Fill rectangle with an ImageBrush

    blueRectangle.Fill = imgBrush;

 

    // Add Rectangle to the Grid.

    LayoutRoot.Children.Add(blueRectangle);

}

Listing 2

Summary

In this article, we saw how to create and use an image brush in Silverlight using XAML and C#.

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
 

The great thing about XAML is that you can easily change the foreground colour of controls, such as a TextBlock, to be exactly what you want it to be. Whether that is through the built-in colour names or a HEX colour is completely your choice.

 

However there may be times when you simply wish to change the colour of a control dependent on the value that it is displaying. In this example we will be using a TextBlock that has it's Text value assigned to it using data context binding.

 

MainPage.xaml

<Page        
    x:Class="MainPage"    
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    xmlns:local="using:TestProject"    
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        
    mc:Ignorable="d">    
    <Page.Resources>    
        <DataTemplate x:Key="listViewItems">    
            <StackPanel>    
                <TextBlock        
                    Margin="5,5,5,5"        
                    Text="{Binding Name}"        
                    Style="{StaticResource BaseTextBlockStyle}"/>    
                <TextBlock        
                    Margin="5,5,5,5"        
                    Text="{Binding Ripeness}"        
                    Style="{StaticResource BaseTextBlockStyle}"/>    
            </StackPanel>    
        </DataTemplate>    
    </Page.Resources>    
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">    
        <ListView        
            x:Name="listViewTest"        
            Margin="5,5,5,5"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Center"        
            ItemsSource="{Binding}"        
            SelectionMode="None"        
            IsItemClickEnabled="False"        
            ItemTemplate="{StaticResource listViewItems}"        
            ContainerContentChanging="listViewUpdated"></ListView>    
        <TextBlock        
            x:Name="listViewNoItems"        
            Margin="5,5,5,5"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Center"        
            Text="There are no fruits in your list to display!"        
            Style="{StaticResource BaseTextBlockStyle}"        
            Visibility="Collapsed"/>    
        <Button        
            Width="150"        
            Height="50"        
            Margin="20"        
            VerticalAlignment="Center"        
            HorizontalAlignment="Right"        
            Content="Clear fruit"        
            Click="clearFruitBasket"/>    
    </Grid>    
</Page>  

 

MainPage.xaml.cs


using System.Collections.ObjectModel;    
using Windows.UI.Xaml;    
using Windows.UI.Xaml.Controls;    
namespace CSharpCornerTestProject     
{    
    public class Fruit     
    {    
        public string Name    
        {    
            get;    
            set;    
        }    
        public string Ripeness     
        {    
            get;    
            set;    
        }    
    }    
    public sealed partial class MainPage: Page     
    {    
        private ObservableCollection < Fruit > fruitList = new ObservableCollection < Fruit > ();    
        public MainPage()     
        {    
            this.InitializeComponent();    
            fruitList.Add(new Fruit()    
            {    
                Name = "Apple", Ripeness = "Ok"    
            });    
            fruitList.Add(new Fruit()    
            {    
                Name = "Banana", Ripeness = "Bad"    
            });    
            fruitList.Add(new Fruit()    
            {    
                Name = "Kiwi", Ripeness = "Rotten"    
            });    
    
            listViewTest.ItemsSource = fruitList;    
        }    
        private void listViewUpdated(ListViewBase sender, ContainerContentChangingEventArgs args) {    
            if (listViewTest.Items.Count == 0)     
            {    
                listViewNoItems.Visibility = Visibility.Visible;    
                listViewTest.Visibility = Visibility.Collapsed;    
            }     
            else     
            {    
                listViewNoItems.Visibility = Visibility.Collapsed;    
                listViewTest.Visibility = Visibility.Visible;    
            }    
           }    
        private void clearFruitBasket(object sender, RoutedEventArgs e)    
        {    
            // clear the fruit list!        
            if (fruitList != null) fruitList.Clear();    
        }    
    }    
}

As I stated above, this is the code base that we used in my previous article about displaying a message once a ListView control no longer has any items in it. We will slightly modify this now so that the ripeness of the fruit in our fruit basket is colour-coded depending on its value.

 

The first thing we need to do is to create a convertor class for us to use when binding data to the list view. This is a very simple affair and just requires you to add a new "Class file" to your project.

 

FruitBasketConvertor.cs

using System;    
using Windows.UI;    
using Windows.UI.Xaml.Data;    
using Windows.UI.Xaml.Media;    
namespace CSharpCornerTestProject.Convertors     
{    
    public class fruitBasketRipenessForegroundConvertor: IValueConverter    
    {    
        public object Convert(object value, Type targetType, object parameter, string language)    
        {    
            string ripeness = (value as string);    
            if (ripeness == "Ok") return new SolidColorBrush(Colors.ForestGreen);    
            else if (ripeness == "Bad") return new SolidColorBrush(Colors.OrangeRed);    
            else if (ripeness == "Rotten") return new SolidColorBrush(Colors.DarkRed);    
            // default return value of lime green      
            return new SolidColorBrush(Colors.LimeGreen);    
        }    
        public object ConvertBack(object value, Type targetType, object parameter, string language)    
        {    
            throw new NotImplementedException();    
        }    
    }    
}  

That is all there is to our file, just those 30 lines. Do take note, however, that we have placed the convertors under their own namespace, CSharpCornerTestProject.Convertors.

 

Using convertors isn't all as daunting as it seems. You create your own custom class, making sure that it derives from IValueConvertor.  Then all we need are two functions.

public object Convert(object value, Type targetType, object parameter, string language)  
{  
    // your convertor code goes here    
}  
public object ConvertBack(object value, Type targetType, object parameter, string language)   
{  
    // your convert back code goes here    
}

The Convert function takes the raw value of your binding and allows you to access anything associated with that, whether it is a class, a string, or anything of your choosing.

 

The ConvertBack function is generally not used all that often and so in our example we are leaving it asthrow new NotImplementedException();. Its main use would be if you wanted to convert the value back to its original state.

 

Returning to the Convert function, this is very simple and there isn't all that much to it at all. All we do here is take the object value and store it into our string variable, ripeness.  

public object Convert(object value, Type targetType, object parameter, string language)   
{  
    string ripeness = (value as string);  
    if (ripeness == "Ok") return new SolidColorBrush(Colors.ForestGreen);  
    else if (ripeness == "Bad") return new SolidColorBrush(Colors.OrangeRed);  
    else if (ripeness == "Rotten") return new SolidColorBrush(Colors.DarkRed);  
    // default return value of lime green      
    return new SolidColorBrush(Colors.LimeGreen);  
}   

Since we have different forms of Ripeness in our Fruit class, we have three separate if statements to determine which colour we should return for our Foreground colour.

 

When converting a Foreground (or Background) XAML member, it expects a SolidColorBrush to be returned and so that is what we are giving it.

 

That is everything that we need to do for the code side of things with our convertor, the next step is much simpler and only requires us to add three new lines of code to the existing MainPage.xaml file that we have.

 

In our Page control, we need to add a new member, highlighted in bold Green.

<Page  
x:Class="MainPage"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="using:rTestProject"  
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    xmlns:utils="using:TestProject.Convertors"  
mc:Ignorable="d">  

This will allow us to access the custom convertor class that we just created in FruitBasketConvertor.cs.

 

Now that we have done that, we need to add our convertor function as a page resource and provide it a key. This will allow us to access it when using the binding convertor. Once again, the addition is highlighted in bold Green.

<Page.Resources>  
    <utils:fruitBasketRipenessForegroundConvertor x:Key="ripenessConvertor"/>  
    <DataTemplate x:Key="listViewItems">  
        <StackPanel>  
            <TextBlock      
                Margin="5,5,5,5"      
                Text="{Binding Name}"      
                Style="{StaticResource BaseTextBlockStyle}"/>  
            <TextBlock      
                Margin="5,5,5,5"      
                Text="{Binding Ripeness}"      
                Style="{StaticResource BaseTextBlockStyle}"/>  
        </StackPanel>  
    </DataTemplate>  
</Page.Resources>

Now that we have given our convertor a key, we can access it anywhere in the MainPage.xaml file when we are binding items. We just have one last thing to do now, that is to add a Foreground member to the TextBlock control that is telling us how ripe our fruit is.

<TextBlock    
    Foreground="{Binding Ripeness, Converter={StaticResource ripenessConvertor}}"    
    Margin="5,5,5,5"    
    Text="{Binding Ripeness}"    
    Style="{StaticResource BaseTextBlockStyle}"/>    

That is everything that we need to do to start dynamically changing the foreground colour of our XAML controls dependent on what the value they're displaying is. If you run the app your fruit basket should now show the Ripeness of each fruit in the three different colours that we assigned earlier on whilst creating our convertor function.

 

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