top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

How to use InitParams in Silverlight?

+3 votes


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


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"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="#FFB7C2E5">
                                <ColumnDefinition Width="0.472*"/>
                                <ColumnDefinition Width="0.025*"/>
                                <ColumnDefinition Width="0.502*"/>
        <ListBox x:Name="myKeysList"/>
        <ListBox x:Name="myValuesList" Grid.Column="2"/>

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()
            App myApp = App.Current as App;

            foreach (string item in myApp.AppParams.Keys)
            foreach (string item1 in myApp.AppParams.Values)

Runnning the Application

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

Figure 1.2 Displaying Key Value pair

posted Jan 12, 2016 by Jdk

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

Related Articles

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.



Go ahead and add a Pie Series into your application.

You can find it in Asset Library.


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:


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






        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:PieSeries Margin="0,0,20,20" d:LayoutOverrides="Width, Height" Title="Pie Chart Sample"IndependentValueBinding="{Binding Path=Key}"

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



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.


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


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.







        <ImageBrush ImageSource="dock.jpg" />



Listing 1

The output looks like Figure 1.



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.



Listing 2


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


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" 

  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. 



  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. 



  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. 



  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. 



  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:


    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:


    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. 




  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">
    <KeySpline ControlPoint1="0,1" ControlPoint2="1,1"/>
    <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0">
    <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
  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 
    Loaded += new RoutedEventHandler(PageLoaded); 

    void PageLoaded(object sender, RoutedEventArgs e) 


  4. That's it. Hit F5 and you should see the ball being thrown and bouncing.

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"



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


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

            <EventTrigger RoutedEvent="Rectangle.MouseEnter">

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



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



                                         From="Yellow" To="Red"                                  





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

               Object at the same time -->

          <EventTrigger RoutedEvent="Rectangle.MouseLeave">



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

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








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



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"   
   Name="GrowButton" Width="80" Height="30">  

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"   
   Name="GrowButton" Width="80" Height="30">  

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"   
   Name="GrowButton" Width="80" Height="30"   
   Delay="500" Interval="100" >  

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"  

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"  
    Title="Window1" Height="300" Width="300">  
    <Grid Name="LayoutRoot">  
        <RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"   
                      Name="GrowButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
        <RepeatButton Margin="100,10,0,0" VerticalAlignment="Top"   
                      Name="ShrinkButton"  Width="80" Height="30"   
                      Delay="500" Interval="100"   
        <Rectangle Name="Rect" Height="100" Width="100" Fill="Orange"/>  

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


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.

  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.

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


  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.

  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.


    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.

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

  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:

  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.

  7. We get the following output:

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.

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