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

meta tags contain useful information that could be used by user’s browser, search engine optimization, Java Script and etc. Some of the most common ones are "keyword" and "Description" meta tags which are used for better optimization.

Changing/Adding these meta tags is particularly useful if you display different data according to user’s setting or your application setting, e.g. if you have more than one language and want to have a different keyword meta tag for each language.

Here is how to add meta tags to your site programmatically:

HtmlMeta htmlMeta = new HtmlMeta();
htmlMeta.Name = "keywords";
htmlMeta.Content = "Tips, Silverlight Tips, SilverlightTips.com";
Page.Header.Controls.Add(htmlMeta);

Above code will generate the following code in your .aspx file:


<meta name="keywords" content="Tips, Silverlight Tips, SilverlightTips.com" />

Posted by Damon Serji on 22. September 2009 17:39 under: Intermediate
 with 0 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

This post explains how to add localization to a Silverlight application.

1. Adding a resource file (.resx) to your Silverlight project
first add a new folder to your Silverlight application and call it anything you like, i.e. LocResources, and then in your Visual Studio add a new Resource File in that folder: Add>New Item>(General category)Resources File. Then, add a new resource to your file, i.e. SiteTitle, and save it. While the resource file is opened, change the Access Modifier to Public (using the combo box).

Now copy and paste the .resx file in your LocResources folder and rename the new file to yourfilename.fr-FR.resx.

Very important: Open your resourcefile.Designer.cs file and change the Constructor to public, i.e. open SiteContent.Designer.cs and change internal SiteContent() to public SiteContent(). This will allow your MainPage to have access to this file.

A .resx file is really nothing but a XML file that contains your content in a format which can be used to localize your application, try opening the .resx file with Notepad to see it for yourself.

Please note, you can call your .resx file anything you like, but unless it is the default language of your site it has to end with the local indicator characters, i.e. if it is French your file has to be called name.fr-FR.resx

2. Add a Resources namespace and a static resource


xmlns:MyResources="clr-namespace:name"

Add the above namespace accordingly, where name is your Silverlight application name. Then add a static resource:


<UserControl.Resources>
   <MyResources:SiteContent x:Name="SiteContent"/>
</UserControl.Resources>

3. Replace the hardcoded text with Static Resources
update Silverlight controls to have the following format where they display text:


Text="{Binding SiteTitle, Source={StaticResource SiteContent}}"

SiteTitle is the name of your resource data, you added this in step 1 in your resource file (.resx). SiteContent is the x:Name we gave to our reference of resource file which we created in step 2.

4. Update the .csproj file of your Silverlight project
open the .csproj file of your Silverlight project in Notepad, locate the SupportedCultures element, at the moment it should not have any value, you will need to change this to a different value if you were going to localize it for a different language than your default language, i.e. you would needed to change this to fr-FR if you were going to localize this for French language, so change this to <SupportedCultures>fr-FR</SupportedCultures> then save and close the file.

5. add InitParameters to the Silverlight control
open your TestPage.aspx (the default page that hosts your Silverlight Control in your web application project), and add InitParameters="UICulture=fr-FR" in order to localize for French. If you are using Object tag add <param name="uiculture" value="fr-FR"/>, and if you are using <asp:Silverlight ... tag add this: InitParameters="UICulture=fr-FR" to your tag.

6. Update App.xaml.cs
copy the following code to the Application_Startup method:

if (e.InitParams.Count > 0)
{
    string cultureName = e.InitParams["UICulture"].ToString();
    if (!String.IsNullOrEmpty(cultureName))
        Thread.CurrentThread.CurrentUICulture =
        new CultureInfo(cultureName);
}

You may need to addthe following namespaces to the top of the page:

using System.Threading;
using System.Globalization;

Run and enjoy!

Posted by Damon Serji on 15. September 2009 22:11 under: Intermediate
 with 2 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

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

this post will give you answer to below questions:

  • How to find/target a Silverlight control which was added through a DataTemplate of a list-based control such as ItemsControl, ComboBox, ListBox or etc.
  • Use Tag property in Silverlight controls to identify different items

In order to identify different controls in your ItemsControl, you could assign a unique identifier (ID) to each control through the "Tag" property.


<ListBox x:Name="lb_test" Width="200" Height="200"
         VerticalAlignment="Top" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Width="190" Tag="{Binding Id}" Text="{Binding Name}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code behind for adding the data:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    List<Items> itemsList = new List<Items>();
    Items it = new Items();
    it.Name = "Damon";
    it.Id = 1;
    itemsList.Add(it);
    Items it2 = new Items();
    it2.Name = "Allan";
    it2.Id = 2;
    itemsList.Add(it2);
    Items it3 = new Items();
    it3.Name = "Rachel";
    it3.Id = 3;
    itemsList.Add(it3);
    lb_test.ItemsSource = itemsList;
}

Create a new class called Items to store Name and Id
public class Items
{
    public string Name {get; set;}
    public int Id { get; set; }
}

and the result:

Now we need to find items inside the ListBox control and apply whatever code we want to them. Here I am going to find the TextBlock for Allan thought the ID I gave it (2) and add an MouseLeftButtonUp event to it, so when we click on Allan we get an alert popup.

First thing we need to do is to add the following line to the end of our MainPage_Loaded method (after the ItemsSource of our ListBox is assigned):

CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

Above line will re-render you layout to force any updates you have done after your xaml was initially rendered.

And here is the method that is called through the above code:

private void CompositionTarget_Rendering(object sender, EventArgs e)
{
    AddEventHandlers(lb_test, -1);
}

And finally the method to find the TexBlock we are looking for, and adding the EventHandler:

private void AddEventHandlers(DependencyObject parent, int childIndex)
{
    DependencyObject child;
    TextBlock textBlock;
    int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    if (parent == lb_test && childrenCount > 0)
    {
        CompositionTarget.Rendering -= CompositionTarget_Rendering;
    }
    for (int index = 0; index < childrenCount; index++)
    {
        child = VisualTreeHelper.GetChild(parent, index);
        if (child is TextBlock)
        {
            textBlock = (TextBlock)child;
            if (textBlock.Tag != null)
            {
                int id = (int)textBlock.Tag;
                if (id == 2)
                {
                    textBlock.MouseLeftButtonUp +=
                    new MouseButtonEventHandler(textBlock_MouseLeftButtonUp);
                    textBlock.Foreground = new SolidColorBrush(Colors.Green);
                }
            }
        }
        else if (child is ContentPresenter)
        {
            AddEventHandlers(child, index);
        }
        else
        {
            AddEventHandlers(child, childIndex);
        }
    }
}

private void textBlock_MouseLeftButtonUp(object sender
, MouseButtonEventArgs e)
{
    TextBlock tb = sender as TextBlock;
    if (tb != null)
    {
        System.Windows.Browser.HtmlPage.Window.Alert(tb.Text + " was
        clicked!"
);
    }
}

In summary, we are passing the x:Name of our ListBox "parent" to the AddEventHandlers and search in its children for any TextBlock controls. If we didn’t find any TextBlock we search in any other searchable controls we find inside that and we do that again until we find all TextBlocks or there is no more controls to search within.

When we find a TextBlock, we check if it has a Tag property and if the value is what we were looking for, if true, we simply add or EventHandler, change color, or do anything we want to do to that TextBlock.

Download the working version of the entire project from here.

Posted by Damon Serji on 30. August 2009 20:02 under: Intermediate
 with 0 Comments