Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating and Using/Reusing User Controls in Silverlight

0.00/5 (No votes)
18 Feb 2011 1  
The creation of a user control that is built with watermark, tooltip and that can be reused in many areas of your app

Creating and using/reusing user controls in Silverlight

The Scenario here presents itself with a need to have a search text box in Silverlight that can potentially be used on various pages and even other projects.

To accomplish such a goal you will create a Silverlight Application and name it ReusingUserControl. You are not going to use the RIA Services, then just accept the default for this exercise. Your page will look like something as below, right?

image001.jpg

On your Silverlight Project add a new folder named CommonControls. Then, Right Click on that new folder and create a new Item, Choose Silverlight User Control and name it UCSearch. Your screen will look like something as below, right?

image002.jpg

For this control, we are going to use a Watermark and also a tooltip with a image and the final result will be something as below:

image003.jpg

image004.jpg

In order for the water mark to work, you will need to use a reference to the System.Windows.Interactivity. Also, you will need to use a CSharp class named Watermark.cs, which I borrow from some nice developer in the web. You also need to have an image as you see above or similar and add it to your project. The final Xaml for that is below. Notice the height and width are made to fit the text area only.

<UserControl x:Class="SilverlightApplicationSideBar.CommonControls.UCSearch"
    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:local="clr-namespace:Watermark"
    xmlns:Interactivity=
        "clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
    mc:Ignorable="d"
    d:DesignHeight="32" d:DesignWidth="172">

    <StackPanel Orientation="Horizontal">
        <TextBox Height="23" Name="tbSearch" Width="160" 
                                       HorizontalAlignment="left" Margin="8,6,2,2" 
                                       VerticalAlignment="Top" 
                                       TextWrapping="Wrap"   >
            <Interactivity:Interaction.Behaviors>
                <local:Watermark Text="Search Area"  Foreground="LightGray" />             
            </Interactivity:Interaction.Behaviors>
            <ToolTipService.ToolTip>
                <ToolTip >
                    <Image Source="/ ReusingUserControl;component/Images/zoomtxt.jpg">
                    </Image>
                </ToolTip>
            </ToolTipService.ToolTip>
        </TextBox>       
    </StackPanel>
</UserControl>

Observe:

  1. Reference to the name space System.Windows.Interactivity.
  2. Declaration of the water mark with what goes with it.
  3. The tooltip service with a reference to the project zoomtxt.jpg image.

Now, how about the code behind?

On the code behind you will have a KeyUp event where you will capture the time when the user presses enter on the keyboard. When the user press enter, the code will check if there is anything on the text, if there is, then the code will set a public property text to the value of that text. Later on, the page that is using your control, will read that public property. For now, see the code behind below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplicationSideBar.CommonControls
{
    public partial class UCSearch : UserControl
    {
        public UCSearch()
        {
            InitializeComponent();
        }

        protected void txtSearchArea_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (tbSearch.Text != null && tbSearch.Text != "")
                {
                    Text = tbSearch.Text;
                }
                else
                {
                    Text = "";
                }
            } 
        }

        public string Text
        {
            get { return tbSearch.Text; }
            set
            {
                Text = value;
            }

        }

    }
}

Remember that you will need the Watermark.cs in order to compile your project.

So far so good, you are ready to use and reuse your user control in other parts of your Silverlight project.

To do that, you will need to declare that user control. Since in this example it is in the same project, you do not need to declare the assembly, but simply the namespace as below:

     xmlns:uc="clr-namespace:ReusingUserControl.CommonControls"

Next, make a reference to your user control on your new page as below:

 <uc:UCSearch Grid.Row="2" Margin="0,15,0,0" x:Name="txtSearch"  
                     KeyUp="txtSearchArea_KeyUp"></uc:UCSearch>

The whole xaml for the main page is displayed below:

<UserControl x:Class="ReusingUserControl.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:uc="clr-namespace:ReusingUserControl.CommonControls"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <uc:UCSearch Grid.Row="2" Margin="0,15,0,0" x:Name="txtSearch"  
                     KeyUp="txtSearchArea_KeyUp"></uc:UCSearch>
    </Grid>
</UserControl>

If you look at the code, you will see that I am making a reference to an event that is being triggered by the keyup, right?

Ok, the code behind is as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace SilverlightApplicationSideBar
{
    public partial class Page2 : Page
    {
        public Page2()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        protected void txtSearchArea_KeyUp(object sender, KeyEventArgs e)
        {       

            if (e.Key == Key.Enter)
            {
                if (txtSearch.Text != null && txtSearch.Text != "")
                {
                    MessageBox.Show(txtSearch.Text);
                }
            }
        }

    }
}

Notice that on keyup, I am checking for the time when the keyup is done. When that is done, I am actually reading the public property named text that I earlier added to my UCSearch control. BOOMMMM! You now get the value of the text box.

What is relevant in this simple demonstration?

  1. The creation of a user control that is built with watermark, tooltip and that can be reused in many areas of your app.
  2. The concept here is to get the entered text and pass to a database to filter the data your project is returning.

Note: To save time and improve productivity, it sounds like that building reusable User Control is one good way to go. What do you think?

I am including the source code, so you can have something to start up with.

Enjoy!

Marcio Coelho

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here