Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.
Recent comments

To set the margin or Canvas of an object from the code you can use SetValue() which is a built-in method. SetValue() takes a DependencyProperty such as a Button, and a double value.

Example:

myButton.SetValue(Canvas.LeftProperty, myPoint.X);

In above example ‘myButton’ is a Button on the xaml, and myPoint is a variable of type Point which we use the X value of.

Posted by Damon Serji on 11. January 2010 18:36 under: Basic
 with 0 Comments

If you want to play music or a short sound clip in Silverlight here is what you need to do:

1. Your sound file
First, make sure you sound file is MP3 or WMA format as other formats are not supported.

Save your file to ClientBin folder (where your xap file gets coppied when buiding the project)

If you dont want to store your file to the ClientBin folder do this: from Visual Studio right click on the sound file and select Properties. Now in Properties window change Build Action to Resource. This ensures the file gets copied to the ClientBin folder during execution.

2. Add a MediaElement in your Xaml file


<MediaElement x:Name="SoundClip" Source="boing.mp3" Volume="1" AutoPlay="False"></MediaElement>

set the Source to be the name of your file and AutoPlay to False so it can be played at click of a button.

Also add a button to play the sound when clicked:


<Button x:Name="PlaySound" Content="Play Sound" />

3. play the sound
in your code behind add this to the Click event of your button:

SoundClip.Play();

If you have any questions please visit Silverlight Forums here: http://silverlightforums.com/showthread.php?p=2080#post2080

Posted by Allan Muller on 10. December 2009 13:16 under: Basic
 with 1 Comments

In order to get the value of your QueryString parameters from the URL all you need is this line of code:

int id = HtmlPage.Document.QueryString["ID"];

And you need to add Windows.Browser namespace for HtmlPage class:

using System.Windows.Browser;

However, there are always two situations which could break your application:

  1. if there are no “ID” parameters in the url
  2. if there is an “ID” parameter in the url, but it has a string value instead of an integer number.

To avoid breaking the code and causing runtime error we need to add a few conditions and also parse the value to integer instead of assigning it right away. We can use Int32.TryParse() method to test the value which we are about to assign to an integer variable before we actually do so, this way we will only assign it if it really is an integer:

int id = -1;
if (HtmlPage.Document.QueryString.ContainsKey("ID"))
{
    string queryStringValue = HtmlPage.Document.QueryString["ID"];
    if (Int32.TryParse(queryStringValue, out id))
    {
        // the result was successful and
        // the correct ID will be inserted to id
    }
    else
    {
        // the result was not successful                   
    }
}

Using above method, you ensure the id gets assigned a value only if the ID parameter in the url has a valid integer value, or it will remain as -1 if the value was not an integer.

Posted by Damon Serji on 30. September 2009 22:30 under: Basic, Intermediate
 with 3 Comments

To set the ZIndex of a Silverlight control programmatically use:

Canvas.SetZIndex(_control, zIndex);

Where _control is your Silverlight control and _zIndex is an integer number which you would like the new ZIndex of your control to be assigned to.

Posted by Damon Serji on 12. September 2009 16:55 under: Basic
 with 2 Comments

DeepLinking is one of the greatest features of Silverlight 3 in my opinion and this post will show you how to add Deep Linking to your Silverlight application in four simple steps:

1. Add Frame control in MainPage.xaml
Add System.Windows.Controls.Navigation in your project References and then a reference to navigation namespace to enable you adding the Frame control.


<UserControl x:Class="SilverlightDeepLinking.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Nav="clr-namespace:System.Windows.Controls;
               assembly=System.Windows.Controls.Navigation"

    mc:Ignorable="d" d:DesignWidth="546" d:DesignHeight="150">
  <Grid Width="546" Height="150" x:Name="LayoutRoot" Background="#FFC2CBD8">
    <Nav:Frame x:Name="MainFrame" UriMapper="{StaticResource uriMapper}"
    HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
  </Grid>
</UserControl>

2. Add URI Routing using UriMapper


<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="SilverlightDeepLinking.App"
             xmlns:Nav="clr-namespace:System.Windows.Navigation;
             assembly=System.Windows.Controls.Navigation"
>
    <Application.Resources>
        <Nav:UriMapper x:Key="uriMapper">
            <Nav:UriMapping Uri="" MappedUri="/HomePage.xaml" />
            <Nav:UriMapping Uri="About" MappedUri="/About.xaml" />
        </Nav:UriMapper>
    </Application.Resources>
</Application>

3. Add your pages to the application
Here I have added a Homepage.xaml and About.xaml and added different content and color to them.

4. Add navigation links to your MainPage.xaml
Since we have Homepage and About page, I am going to add to HyperlinkButtons on my MainPage.xaml in order to enable me browse to my two different pages. Please note, the Homepage and About pages will appear inside your <Nav:Frame control, therefore we should have our navigation links i.e. on top/bottom and have the Frame in the middle, where the content will be displayed.

Here is the MainPage.xaml after adding the HyperlinkButtons and adjusting the layout:


<Grid Width="546" Height="150" x:Name="LayoutRoot" Background="#FFC2CBD8">
    <HyperlinkButton x:Name="HomeLink" Content="Homepage"
    HorizontalAlignment="Center" Margin="0,2,60,0" Height="15"
     VerticalAlignment="Top" Background="#009A480E"
     Foreground="#FFC55314" />
    <HyperlinkButton x:Name="AboutLink" Content="About"
     HorizontalAlignment="Center" Margin="60,2,0,0" Height="15"
     VerticalAlignment="Top" Foreground="#FFC55314" />
    <Nav:Frame x:Name="MainFrame" UriMapper="{StaticResource uriMapper}"
    HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
     Margin="0,20,0,0" />
</Grid>

Add the code behind MainPage.xaml.cs

public MainPage()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    HomeLink.Click += new RoutedEventHandler(HomeLink_Click);
    AboutLink.Click += new RoutedEventHandler(AboutLink_Click);
}
private void AboutLink_Click(object sender, RoutedEventArgs e)
{
    MainFrame.Navigate(new Uri("About", UriKind.Relative));
}
private void HomeLink_Click(object sender, RoutedEventArgs e)
{
    MainFrame.Navigate(new Uri("", UriKind.Relative));
}

When you click on the About link, you will navigate away from the current page, note the "#About" at the end of the URL.

The complete project can be downloaded from here.

Posted by Damon Serji on 6. September 2009 12:48 under: Basic
 with 3 Comments

As well as demonstrating how to create a simple Tooltip control for your application, this post will also show you how to get/set the absolute position of a control in your application even if it is not a Canvas control.

The idea of tooltip is really to display some information such as images or text, when you hover the mouse on a control, and hide when you hover out.

To this, all we need to do is to change the Visibility of our control which contains that information to visible/collapse when the mouse if hovered/left.

I am going to put my information in a separate xaml file called Tooltip.xaml.


<UserControl x:Class="SilverlightPositioningNoneCanvasControl.Tooltip"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="70" Height="40">
    <Grid x:Name="LayoutRoot" Background="Pink"  Width="70" Height="40">
        <TextBlock Text="My Tooltip" Foreground="Chocolate"
        VerticalAlignment="Center" HorizontalAlignment="Center" />
    </Grid>
</UserControl>

I will then add a reference to the tooltip in my MainPage.xaml file with Visibility set to Collapsed.


<UserControl x:Class="SilverlightPositioningNoneCanvasControl.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SilverlightPositioningNoneCanvasControl"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="300" d:DesignHeight="280">
  <Grid x:Name="LayoutRoot" Width="300" Height="280" Background="Azure">
        <TextBlock x:Name="tb_Tooltip" Text="Hover me" Margin="40" Width="54"
        Height="14" HorizontalAlignment="Left" VerticalAlignment="Top" />
        <TextBlock x:Name="tb_Tooltip2" Text="Hover me" Margin="40" Width="54"
        Height="14" HorizontalAlignment="Right"  VerticalAlignment="Bottom"/>
        <local:Tooltip x:Name="TooltipWindow" Visibility="Collapsed"
        VerticalAlignment="Top" HorizontalAlignment="Left" />
  </Grid>
</UserControl>

Now from my code behind (MainPage.xaml.cs) I can easily control the Visibility of my tooltip control by using MouseEnter and MouseLeave events.

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    tb_Tooltip.MouseEnter += new MouseEventHandler(tb_tooltip_MouseEnter);
    tb_Tooltip.MouseLeave += new MouseEventHandler(tb_Tooltip_MouseLeave);

    tb_Tooltip2.MouseEnter += new MouseEventHandler(tb_tooltip_MouseEnter);
    tb_Tooltip2.MouseLeave += new MouseEventHandler(tb_Tooltip_MouseLeave);
}

private void tb_Tooltip_MouseLeave(object sender, MouseEventArgs e)
{
    TooltipWindow.Visibility = Visibility.Collapsed;
}

private void tb_tooltip_MouseEnter(object sender, MouseEventArgs e)
{
    TooltipWindow.Visibility = Visibility.Visible;
}

As you can see from the screen shot above, the tooltip appears at the top left corner of the application if you hover your mouse on any of the "Hover me" text. So what I am going to do, is to capture the position of the "Hover me" text which the mouse is hovering, and make some calculations to workout where to display my tooltip window, and finally reposition my tooltip control before I set its visibility to Visible:

private void tb_tooltip_MouseEnter(object sender, MouseEventArgs e)
{
    TextBlock tb = sender as TextBlock;
    GeneralTransform transform = tb.TransformToVisual(LayoutRoot);
    Point position = transform.Transform(new Point(0, 0));
    double senderHeight = tb.ActualHeight;
    double senderWidth = tb.ActualWidth;

    double x = position.X;
    double y = position.Y;

    int gap = 3;

    if (x + TooltipWindow.Width + senderWidth + gap > LayoutRoot.ActualWidth)
    {
        x = position.X - TooltipWindow.Width - gap;
    }
    else
    {
        x = position.X + senderWidth + gap;
    }

    if (position.Y + senderHeight + TooltipWindow.Height >
    LayoutRoot.ActualHeight)
    {
        y = position.Y - TooltipWindow.Height + tb.Height / 2;
    }
    else
    {
        y = position.Y + tb.Height / 2;
    }

    TooltipWindow.Margin = new Thickness(x, y, 0, 0);

    TooltipWindow.Visibility = Visibility.Visible;
}

and the result for hovering on both "Hover me" text:

As you can see, the tooltip is displayed on the bottom-right of the top-left text and on the top-left of the bottom text when you hover the mouse on them. This is done by some simple calculation and comparing the final X and Y positions to the Width and Height of the main application's container control, in this case a Grid called LayoutRoot.

In order to get the coordinates of the "Hover me" text, I first had to have a transform object, so I used .TransformToVisual method and passed it the control that contains my TextBlock (LayoutRoot). I then used .Transform method to get the current position of my GeneralTransform opbject according to the very top left position of my LayoutRoot container.

Finally I set the position of my tooltip by changing its margin with new X and Y values.

Download the working version of the entire project from here

Posted by Damon Serji on 1. September 2009 19:06 under: Basic
 with 1 Comments

How to programmatically add a 'mailto' link in silverlight:

Add the below line to your .xaml.cs file to open mailto (email link) when an event gets fired (i.e. HyperlinkButton is clicked or etc):

HtmlPage.Window.Navigate(new Uri("mailto:tips@silverlighttips.com"));

if HtmlPage is not recognised in your Visual Studio, it is because you are missing an assemblly reference, so simply add this reference to the very top of your page:

using System.Windows.Browser;

Posted by Damon Serji on 24. August 2009 16:44 under: Basic
 with 5 Comments