Home   Subscribe   Linkedin
  Archive Contact  

How to create Silverlight Custom Control - control library

The article describes how to create a Silverlight custom control or control library in Silverlight 4.

I am going to demonstrate how to create a “Login Box” inside a control library which we can then place on a childwindow

Step 1: Create a Simple Silverlight Application, lets name is MySilverlightApplication

image

Let it create an Asp.net web application MySilverlightApplication.Web for the hosting purpose.

Step 2: Open up the MainPage.xaml and design a small Login screen as you would normally do.

And it looks something like this

image

Remember we will not create any event handlers here.

Step 3: Add a new project of type “Silverlight control library” into the solution.

let the name on the new project be MySilverlightApplication.Library

image

Choose the version of library as Silverlight version 4 on the window that comes after this screen.

By Now the solution should something like this

image

Step 4: Add a new folder in MySilverlightApplication.Library by the name of “Themes” into the class library project and add a Resource Dictionary file by the name of “generic.xaml” inside the themes folder (Remember the names cannot be anything else than “Themes” and “generic.xaml” though you can change the case if you wish to)

image

Step 5: Delete Class1.cs from MySilverlightApplication.Library and add a new class by the name of “MyLoginScreen.cs” and inherit this class by System.Windows.Controls.Control.

now this class is going to be our custom control in the library we are creating and of course you can have more than one controls in one single library

image

Step 6: Tell  the control class what its design looks like, in its constructor and add an override where we are going to find the elements later

image

Step 7: Provide the design to the control, so will go ahead and create a style in the resource dictionary (generic.xaml) whose target type is our control  (MyLoginScreen in this case)

image

 

Step 8: Cut and paste the entire Grid of login screen that we created in step 2. into Control template of the style in generic.xaml

image

 

Step 9: Our next step is to find the elements in the control which are supposed to be there in the style like “TxtUserName”, etc.

Create exactly the  same elements in MyLoginScreen class say if “TxtUserName” is a TextBox, we will create a TextBox in MyLoginScreen.cs by the name of “TxtUserName” you can keep the names different if you wish to, but I'm going to use the same name in order to avoid any confusion, and then we will try finding the elements in the “OnApplyTemplate” override method.

Something like this.

using System.Windows.Controls;

namespace MySilverlightApplication.Library
{
    public class MyLoginScreen : Control {
        private bool _isTemplateApplied;
        private TextBox TxtUserName;
        private PasswordBox TxtPassword;
        private Button LoginButton;


        public MyLoginScreen()
        {
            _isTemplateApplied = false;
            DefaultStyleKey = typeof(MyLoginScreen);
        }

        public override void OnApplyTemplate()
        {
            if (_isTemplateApplied) return;
            base.OnApplyTemplate();

            TxtUserName = GetTemplateChild("TxtUserName") as TextBox;
            TxtPassword = GetTemplateChild("TxtPassword") as PasswordBox;
            LoginButton = GetTemplateChild("LoginButton") as Button;


            _isTemplateApplied = true; 
        }
    }
}


Step 10: Create Properties which are accessible from Silverlight UI (xaml) where we place the control and the event handlers to handle the events inside the custom control

In order to hold the values of the properties, we need to tie them up to some dependency property and so we need as many dependency properties as the number of properties that we create. (just one in this case)

public static readonly DependencyProperty LoginButtonContentProperty = DependencyProperty.Register(
    "LoginButtonContent", typeof(string), typeof(MyLoginScreen), new PropertyMetadata(OnLoginButtonContentChanged));

public string LoginButtonContent 
{
    get { return GetValue(LoginButtonContentProperty) as string; }
    set { SetValue(LoginButtonContentProperty, value); }
}

private static void OnLoginButtonContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var myLoginScreen = d as MyLoginScreen;
    if (myLoginScreen.LoginButton != null) myLoginScreen.LoginButton.Content = e.NewValue as string;
}

 

A custom event type which we will send parameters across the control (username and password in this case).

public class MyEventType : EventArgs {
    public string UserName { get; set; }

    public string Password { get; set; }
}

event handler to capture Login button’s click

public event EventHandler<MyEventType> LoginClicked;

private void Login_Clicked(object sender, RoutedEventArgs e)
{
    if (LoginClicked != null)
        LoginClicked(sender as Button, new MyEventType {
                                               UserName = TxtUserName.Text,
                                               Password = TxtPassword.Password
                                           });
}

 

Step 11. Wrap the content property and the event handler to the login button

public override void OnApplyTemplate()
{
    if (_isTemplateApplied) return;
    base.OnApplyTemplate();

    TxtUserName = GetTemplateChild("TxtUserName") as TextBox;
    TxtPassword = GetTemplateChild("TxtPassword") as PasswordBox;
    LoginButton = GetTemplateChild("LoginButton") as Button;

    if (LoginButton != null)
    {
        LoginButton.Content = LoginButtonContent;
        LoginButton.Click += Login_Clicked;
    }

    _isTemplateApplied = true; 
}

 

Step 12: Build the MySilverlightApplication.Library project and add its reference to MySilverlightApplication project

image

 

Step 13: Add the Control to the silverlight page

Go back to the mainpage.xaml  of MySilverlightApplication project. If you did a cut an paste to generic.xaml file then there must be nothing in there in terms of UI Element so lets create a grid in there,  and if not then lets remove everything else and leave only the topmost grid.

Now we need to add a xml namespace into the mainpage.xaml which will point towards our Library. In our case it is going to be something like this

xmlns:Library="clr-namespace:MySilverlightApplication.Library;assembly=MySilverlightApplication.Library" 

and then simply call the “MyLoginBox” from Library inside grid like this,

<UserControl x:Class="MySilverlightApplication.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:Library="clr-namespace:MySilverlightApplication.Library;assembly=MySilverlightApplication.Library"
mc
:Ignorable="d">
<
Grid x:Name="LayoutRoot" Background="White">
<
Library:MyLoginScreen />
</
Grid>
</
UserControl>

 

Step 14 Customize the Control using the properties which were created in step 10 and tie up the Event Handlers

We created a property for the purpose of changing the Login Button Contents and an event handler which should get invoked when the login button is clicked. Lets see how that works. Also I have added a small code to show the username and password in a MessageBox when the login button gets hit.

image

 

Step 15: Run the Application.

When we Run the application this is what comes up.

image

I have attached the sample application along with this post.

Hope it helps someone.

MySilverlightApplication.zip (21.69 kb)

Posted by: Zeeshan

Categories: Control Library, Custom Control, Silverlight

Tags: , ,