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

Extension methods are great way to add and use custom functionality on your objects.

So what is an Extension method?

In a short and simple describing: instead of creating a method that takes an instance of your object, applies your changes and then returns you the instance of that control, you can create an Extension method for that specific object to do the same thing but in a way of built-in within your object.

Example: if we had a TextBox that needed to have a valid text input:


<TextBox x:Name=”InputEmail/>

And you have:

string inputEmail = InputEmail.Text;

You can do:

If (inputEmail != “” && ValidateEmail(inputEmail) == true)
{
   .
   .
}
.
.
private bool ValidateEmail(string getInputEmail)
{
   .
   .
}

or you can do it in a much cleaner and easier to understand way using “IsEmailValid” extension, which extends the string:

if (inputEmail.IsEmailValid())
{

}

You can immediately notice from the above example that how much time and line of codes you will save by simply using Extensions instead of re-writing your custom methods to apply the same operation on a common object or element within a project that uses that feature in many places.

How to add an Extension method to Silverilght objects?

First we need to add a new static class that contains a static method for our new Extension method (IsEmailValid).

public static class FrameworkElementExtensionExtensions
{
    public static bool IsEmailValid (this string getInputEmail)
    {
        bool isMatched = true;
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        
        if (getInputEmail != “” && regex.IsMatch(s))
        {
            isMatched = false;
        }
        return regex.IsMatch(s);
    }
}

Note in the IsEmailValid method we used the keyword “this” before string getInputEmail, this simply means the IsEmailValid Extension method belongs to objects of type “string”.

To use the above extension method anywhere within your project, all you have to do is to import the reference to any of your classes, where you like the extension to be available, by adding “using FrameworkElementExtensionExtensions;” to that class.

Now you should even get the IsEmailValid method in your Visual Studio Intellisense when you add a dot after any string variable. So now you could simply do:

if (inputEmail.IsEmailValid()){
    HtmlPage.Window.Alert("Email was successfully submitted!");
}

Above example was a very simple example, I will update the example solution regularly to include more advanced examples for you to use (copy & paste!) in the future, so please check this post later for updates. Also, this example, along with more examples in the future, is available to download from CodePlex from here.

Posted by Damon Serji on 6. October 2009 09:37 under: Intermediate
 with 0 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

Gavin Wignall at Silverlight Buzz is doing a series of posts on his blog, aiming to cover the most useful information and techniques on Expression Blend for both beginners and pros. For more information, and to see the list of topics, which will be posted through the whole October, visit Learn Expression Blend in a Month! at SilverlightBuzz.com.

Posted by Damon Serji on 30. September 2009 21:26 under: Silverlight News
 with 1 Comments

In this example I will demonstrate how to use ImageBrush to fill area of shapes like rectangle or ellipse with an image.

In order to fill the area of a control like Rectangle control, we need to create an instance of type BitmapImage, and this is not possible if we do not have a Uri which points to a real image file.

So first, I create an Uri pointing to an image which I had put in the “images” folder in my Silverlight application project.

Hint: try to use Uri.TryCreate to create your Uri as by this way you stop your application from breaking if the path you gave your Uri was not valid or did not exist.

Second, create a new instance of BitmapImage and assign your Uri to its value.

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}

Now you can create a new instance of ImageBrush and assign your created BitmapImage to its ImageSource value:

ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = image;

Finally, using .Fill method on your Rectangle control fill the entire rectangle (or any other shapes your object is) with your ImageBrush. And here is how your final code should look like:

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}
if (image != null)
{
    ImageBrush imageBrush = new ImageBrush();
    imageBrush.ImageSource = image;
    Logo.Fill = imageBrush;
    LogoEllipse.Fill = imageBrush;
    LogoRectangle.Fill = imageBrush;
}

Download this project from CodePlex from here. Here it is working:

Posted by Damon Serji on 28. September 2009 13:42 under: Intermediate
 with 2 Comments
Get Microsoft Silverlight

Silverlight Child Window is a great new feature which enables you to use advantage of a fully enhanced popup window. Child Window can be customized just like a normal xaml file to display or request information from the user. In this post I will explain briefly how receive and save information entered by user from a Child Window (ChildWindowForm.xaml in our example) and then display them in the parent window (MainPage.xam).

I am going to create an example in which user enters his/her name and surname in a Child Window and once submitted different details, along with the entered name and surname, are displayed in the main page.

I have uploaded the working example of this post to CodePlex and you can download it from here to test it for yourself.

1. add a new Child Window
in Visual Studio = right click on your Silverlight project, then, Add > New Item > Silverlight Child Window. The Child Window will have an OK and a Cancel button by default when it is created. Add two TextBox controls to the page for users to enter their name and surname.

2. Create an EventHandler in Child Window
code to create a new EventHandler:

public event EventHandler SubmitClicked;

3. Create public properties to save the values
it is possible to access the value of the TextBox controls we added in the Child Window directly from the MainPage.xaml.cs, however, this is a terrible practice as it will reduces your code stability in the future. Therefore create two public properties of type string to save the value of both TextBox controls. You will notice in my project I save the value of the TextBox in a private string variable and then save that variable to my public – this is just a better practice for coding so don’t get confused.

public string NameText
{
    get { return _nameText; }
    set
    {
        _nameText = value;
    }
}
public string SurnameText
{
    get { return _surnameText; }
    set
    {
        _surnameText = value;
    }
}


4. Fire the event once submit button is clicked in Child Window
there should already be a method for when the OK (Submit) button is pressed, it is called OKButton_Click. Inside that we need to fire the event which we created earlier, so that our event gets fired when the code reaches this method i.e. when we press OK in Child Window.

private void OKButton_Click(object sender, RoutedEventArgs e)
{
    if (SubmitClicked != null)
    {
        _nameText = Name.Text;
        _surnameText = Surname.Text;
        SubmitClicked(this, new EventArgs());
    }
    this.DialogResult = true;
}


5. In MainPage.xaml create a new instance of the Child Window

in order to display your Child Window first create a private variable your Child Window type - what ever you called your Child Window file will be the type of your variable i.e. ChildWindowForm.xaml:

private ChildWindowForm childWindowForm;

now create a new instance of it:

childWindowForm = new ChildWindowForm();


6. How to show Child Window
you need to display the actual Child Window which you created and have the instance in your MainPage. To do that, use the instance you just created and call the build-in method for any Child Window called “Show”:

childWindowForm.Show();


7. In MainPage.xaml hook up the submit event in Child Window
now we have an event which will get fired up from the Child Window when we click the submit button (OK button). All we have to do is to wire that event up so that we can do something when it is fired:

childWindowForm.SubmitClicked += new
EventHandler(childWindowForm_SubmitClicked);


8. Access the properties of the Child Window

private void childWindowForm_SubmitClicked(object sender, EventArgs e)
{
    Name.Text = childWindowForm.NameText;
    Surname.Text = childWindowForm.SurnameText;
}



I have skipped explaining some features that you will see in the example I created for this project (download from here) to concentrate more on the subject of this post. However if you have any questions about this post or the example please do feel free to post your comments and I will try to help as much as I can.

Posted by Damon Serji on 24. September 2009 21:27 under: Intermediate
 with 8 Comments

In order to call a function that you created in your .HTML or .ASPX file (which hosts your Silverlight application), you need to Invoke that function by using Invoke method in System.Windows.Browser.HtmlPage namespace:

HtmlPage.Window.Invoke("yourFunction");

If you want to pass some parameter to that function, simply add the parameters to the method using comma.

HtmlPage.Window.Invoke("yourFunction", param1, param2);

Posted by Damon Serji on 22. September 2009 17:29 under: Intermediate
 with 1 Comments

The trick is to capture the selected index of the item which has been clicked, and then assign it back to the ListBox control by using .SelectedIndex method.

The only thing I needed to do extra was to assign the .SelectedIndex to 0 before I assign it back to the actual selected index.

Also, you will see in this example that I am capturing the selected index number on .MouseLeftButtonUp of TextBlocks which are my LibBox’s items, you could off course capture this information on .Click or . MouseLeftButtonUp of any other control in your ListBox items.
You can download the working project from here.

To test the project click on an item in the ListBox, then click on Loose Focus button, and then click on Focus button to bring the focus back to the ListBox.

Posted by Damon Serji on 15. September 2009 10:33 under: Intermediate
 with 0 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

How to change the state of a Silverlight control to go to a different VisualState in your VisualStateManager programmatically?

Let's say you have a VisualStateManager in your Style which has TargetType="Button" and defines different VisualStates for different events, i.e. MouseOver, Pressed, Disabled and Normal. They of course work when you mouse hover the button or press it, but if you decided to force the button to change its state from the code here is the code you need:

VisualStateManager.GoToState(_YourButton, "Normal", true);

Posted by Damon Serji on 11. September 2009 13:43 under: Intermediate
 with 0 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