Tip/Trick: Creating and Using Silverlight and WPF User Controls

One of the fundamental design goals of Silverlight and WPF is to enable developers to be able to easily encapsulate UI functionality into re-usable controls.

You can implement new custom controls by deriving a class from one of the existing Control classes (either a Control base class or from a control like TextBox, Button, etc).  Alternatively you can create re-usable User Controls - which make it easy to use a XAML markup file to compose a control's UI (and which makes them super easy to build).

In Part 6 of my Digg.com tutorial blog series I showed how to create a new user control using VS 2008's "Add New Item" project item dialog and by then defining UI within it.  This approach works great when you know up front that you want to encapsulate UI in a user control.  You can also use the same technique with Expression Blend.

Taking Existing UI and Encapsulating it as a User Control

Sometimes you don't always know you want to encapsulate some UI functionality as a re-usable user control until after you've already started defining it on a parent page or control.

For example, we might be working on a form where we want to enable a user to enter shipping and billing information.  We might begin by creating some UI to encapsulate the address information.  To-do this we could add a <border> control to the page, nest a grid layout panel inside it (with 2 columns and 4 rows), and then place labels and textbox controls within it:

After carefully laying it all out, we might realize "hey - we are going to use the exact same UI for the billing address as well, maybe we should create a re-usable address user control so that we can avoid repeating ourselves". 

We could use the "add new item" project template approach to create a blank new user control and then copy/paste the above UI contents into it. 

An even faster trick that we can use within Blend, though, is to just select the controls we want to encapsulate as a user control in the designer, and then "right click" and choose the "Make Control" menu option:

When we select the "Make Control" menu item, Blend will prompt us for the name of a new user control to create:

We'll name it "AddressUserControl" and hit ok. This will cause Blend to create a new user control that contains the content we selected:

When we do a re-build of the project and go back to the original page, we'll see the same UI as before - except that the address UI is now encapsulated inside the AddressUserControl:

We could name this first AddressUserControl "ShippingAddress" and then add a second instance of the user control to the page to record the billing address (we'll name this second control instance "BillingAddress"):

And now if we want to change the look of our addresses, we can do it in a single place and have it apply for both the shipping and billing information.

Data Binding Address Objects to our AddressUserControl

Now that we have some user controls that encapsulate our Address UI, let's create an Address data model class that we can use to bind them against.  We'll define the class like below (taking advantage of the new automatic properties language feature):

Within the code-behind file of our Page.xaml file we can then instantiate two instances of our Address object - one for the shipping address and one for the billing address (for the purposes of this sample we'll populate them with dummy data).  We'll then programmatically bind the Address objects to our AddressUserControls on the page.  We'll do that by setting the "DataContext" property on each user control to the appropriate shipping or billing address data model instance:

Our last step will be to declaratively add {Binding} statements within our AddressUserControl.xaml file that will setup two-way databinding relationships between the "Text" properties of the TextBox controls within the user control and the properties on the Address data model object that we attached to the user control:

When we press F5 to run the application we'll now get automatic data-binding of the Address data model objects with our AddressUserControls:

Because we setup the {Binding} declarations to be "Mode=TwoWay", changes users make in the textboxes will automatically get pushed back to the Address data model objects (no code required for this to happen). 

For example, we could change our original shipping address in the browser to instead go to Disneyland:

If we wire-up a debugger breakpoint on the "Click" event handler of the "Save" button (and then click the button), we can see how the above TextBox changes are automatically reflected in our "_shippingAddress" data model object:

We could then implement the SaveBtn_Click event handler to persist the Shipping and Billing Address data model objects however we want - without ever having to manually retrieve or manipulate anything in the UI controls on the page.

This clean view/model separation that WPF and Silverlight supports makes it easy to later change the UI of the address user controls without having to update any of our code in the page.  It also makes it possible to more easily unit test the functionality (read my last post to learn more about Silverlight Unit Testing).

Summary

WPF and Silverlight make it easy to encapsulate UI functionality within controls, and the user control mechanism they support provides a really easy way to take advantage of this.  Combining user controls with binding enables some nice view/model separation scenarios that allow you to write very clean code when working with data.

You can download a completed version of the above sample here if you want to run it on your own machine. 

To learn even more about Silverlight and WPF, check out my Silverlight Tutorials and Links Page.  I also highly recommend Karen Corby's excellent MIX08 talk (which covers User Controls, Custom Controls, Styling, Control Templates and more), which you can watch online for free here.

Hope this helps,

Scott

37 Comments

  • Hi Scott, great article, as always.

    Could you please do a blog on writing your own Silverlight controls and using them in ASP.Net, setting properties using control tags and setting and reading properites in code, handling events on the server after a postback, etc. Much like ASP.Net user controls.

    Thank you very much.

  • Thanks for the article! I like the "Make Control" feature, it's really awesome.

  • Nice article! is it possible do the same but instead of a user control have the tool generate a custom control?

    Maybe that would be hard to implement because custom controls require a different approach than the markup/codebehind dependency of user controls.

  • Great Post again. Thanks for sharing the information. I love your series about Silverlight 2.
    One question:How would one implement validation (or a concept for validation) for this example. As far as I know SL 2b1 does not come with the IDataErrorInfo interface and the validation concepts which are covert in WPF. Are there plans to implement that? Or is there some other way to use with SL2?....

  • Thanks Scott, any tricks on how to add silverlight controls to a MS MVC view page ? I thought it would be simple but nothing showed up :) (I want to pass a value to the silverlight control via a querystring and then save off this form)

  • Great as always

  • I have been looking through your posts for a while and find them interesting and valuable. I have one question though, i really like the color scheme you are using in VS, is that something you have for download or are you willing to share it? Maybe you already have but i haven't found it yet?

  • Hi Scott,

    Very Fine Article.I tried opening your sample code file in Visual Studio2008, I could not open.It is opening fine in Expression Blend..But the other way should be also possible.Can you help me?

  • What's great about these binding expressions is that they are almost identical to Adobe Flex's binding expressions. Thanks for making it easier to switch back and forth between the two platforms.

    Someday in the future, someone will build an IDE that can target either Silverlight or Flex builder...

  • What the hell is in tow last posts ?

  • You're designing skills are getting better Scott!

    Good article.

    -Daveloper

  • Scott,

    Great article! Thanks for sharing.

  • Scott... I noticed that you posted this blog at 1:30 AM and had 2 comments by 5:30 AM... I don't know what you all are taking, but can I have some?! Thanks as always!!!

  • Hi Hugo,

    >>>>> Could you please do a blog on writing your own Silverlight controls and using them in ASP.Net, setting properties using control tags and setting and reading properites in code, handling events on the server after a postback, etc. Much like ASP.Net user controls.

    I will try and put that on the list!

    Thanks,

    Scott

  • Hi Jacek,

    >>>>>> What about UserControl in assemlby (as a dll)? Is there any option to do this or I have to copy "generated" UserControl manualy to ClassLibrary project?

    User controls in WPF and Silverlight actually compile down to assemblies (no loose .XAML file required). This makes them easier to package up and re-use then say ASP.NET user controls (where you still need the .ascx file around to use them). You can optionally create a class library to encapsulate 1 or more user controls and then redistribute them that way.

    Hope this helps,

    Scott

  • Hi Torkel,

    >>>> Nice article! is it possible do the same but instead of a user control have the tool generate a custom control? Maybe that would be hard to implement because custom controls require a different approach than the markup/codebehind dependency of user controls.

    I responded to Jacek who had a similar question (see above). The good news is that user controls do compile down to assemblies by default, so you can easily copy them without having any markup dependencies.

    Hope this helps,

    Scott

  • Hi Felix,

    >>>>>> One question:How would one implement validation (or a concept for validation) for this example. As far as I know SL 2b1 does not come with the IDataErrorInfo interface and the validation concepts which are covert in WPF. Are there plans to implement that? Or is there some other way to use with SL2?....

    Silverlight 2 Beta1 doens't have built-in validation support with binding expressions. The good news, though, is that this support is being added for beta2.

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> Thanks Scott, any tricks on how to add silverlight controls to a MS MVC view page ? I thought it would be simple but nothing showed up :) (I want to pass a value to the silverlight control via a querystring and then save off this form)

    You should be able to just declare a Silverlight control on a MVC view page using an object tag. You can then optionally pass parameters to the control using a param element within it. The silverlight control can then access the values as part of its startup.

    Hope this helps,

    Scott

  • Hi Michael,

    >>>>>>> I have been looking through your posts for a while and find them interesting and valuable. I have one question though, i really like the color scheme you are using in VS, is that something you have for download or are you willing to share it? Maybe you already have but i haven't found it yet?

    Here is a copy of my VS settings file with the above color scheme that you can download and use: http://www.scottgu.com/blogposts/extractusercontrol/vssettings.zip

    Hope this helps,

    Scott

  • Hi Hemant,

    >>>>>>> Very Fine Article.I tried opening your sample code file in Visual Studio2008, I could not open.It is opening fine in Expression Blend..But the other way should be also possible.Can you help me?

    You need to make sure you have the VS 2008 Tools for Silverlight installed. Bradley Bartz has a pointer here in case you run into any problems with installing this: http://weblogs.asp.net/bradleyb/archive/2008/03/06/installation-tips-for-sivliverlight-tools-beta-1-for-visual-studio-2008.aspx

    Hope this helps,

    Scott

  • Hi VinneyK,

    >>>>>>> Scott... I noticed that you posted this blog at 1:30 AM and had 2 comments by 5:30 AM... I don't know what you all are taking, but can I have some?! Thanks as always!!!

    Coffee...lots of coffee. ;-)

    Thanks,

    Scott

  • Thanks for the VS settings file too.

  • I love that you have Microsoft as the shipping address and Apple as the billing address in your example.

  • Hi Steve,

    >>>>>>> Scott, I would really appreciate it if you took a quick look at this post: silverlight.net/.../13424.aspx

    I just sent email to someone on the team to ask them to take a look at this question.

    Thanks,

    Scott

  • Scott, your UI design skills are getting a little too advanced! I MISS COMIC-SANS!!!

    :)

  • am I the only one that noticed the Bill to address is Apple's headquarters? LOL

  • Scott, will Silverlight support bitmap drawing? Many people here need the plain old SetPixel() and GetPixel() to draw cool effects.

  • Does Silverlight and WPF User Controls like ASP.NET User Control (.ascx)?

  • Does your silverlight team have plan to expose directx ,opengl or other better api about graphic? yes i know there have some graphic object exists now,but right now im blocked on the performance problem when i make a game ,could not go ahead anymore.

    I have write a test game (www.douziwang.cn) .

    So.Genteel man could you kindly tell me can i wait for the new feather of graphic api been add .

    Thanks a lot.

  • Im just finished main part of my teris game using silverlight. When there are not too much graphic object it's seem work well ,but when the amount of graphic object grown the speed will slow down,Does silverligtht have some sample api to directly draw on some canvas rather than to create a per object for per graphic cell.

    Does silverlight plan to support directx or opengl (Im dreaming it very night,Can your team give me have a pretty dream ,Thanks and long live your team).

    This link is the test link of the game,If you have a quick view of the game(I have reduce the cell to 16*8 ) . (www.douziwang.cn)

    thanks for your help

  • Do you know of a migration path from .NET 2.0 WinForms to .NET 3.5 WPF using Blend toolset and including Silverlight within ?

  • Hey Scott, couple questions that I've scoured the web for and cannot find.

    1) Have you had any luck getting your ScrollViewers to work with the mouse wheel?

    2) Any plans for text in TextBlocks to be selectable?

    3) Context menus? It would be nice to offer the ability to copy/paste/save images.

    4) Command line arguments from HTML? It would be nice to be able to split up Silverlight-only sites into pages linkable from HTML, so you'd need some way to pass arguments in when starting the app.

  • thanks for the great silverlight examples. I have few questions about silverlight usability..

    1. Is silverlight 2.0 is going to replace asp.net / ajax type development. (all computers installed silverlight 2)
    2. If i develop a large application using silverlight (eg. an accouting software), is it possible to load different user entry screen (eg. customer data entry) dynamically rather than store all UI in one large .xap file. or i should use different .aspx file to host individual .xap conponetents (data entry) of a large application.

    or i am an idiot silverlight should be use small things, and should use as a part of asp.net app.

    thanks
    achu.

  • Very helpfull. Thanks


    Josh Coswell
    http://riverasp.net

  • Hi, would you be able to provide a link or something for me to read up on how to dynamically add a custom silverlight control, i.e. in code.

    Thanks,
    Tyrone

  • Scott,
    I went to the Heroes Happen Here launch in Phoenix last week, and there was a demo during the keynote speakers of a "Coffee" house application using silverlight. Have you seen this demo, and if so, do you know where I could see the application? I am trying to show a good example of Silverlight to my manager and this would demonstrate some of the features we want on our upcoming commerce site.

    Thanks,
    Charles

  • As always a great article but we are worried about the Application size and as such I have been investigating on demand loading of controls (http://msdn.microsoft.com/en-us/library/cc296243(vs.95).aspx). There are some good examples out there like http://jimmangaly.blogspot.com/2008/04/using-webclient-to-download-content-on.html and I have modified your UserControl example to be on-demand loaded. See my blog at jrmcfetridge.blogspot.com . All this works great and as advertised however the control must be in the same solution as the consumer. In reality must corporate environments like our want shared libraries of UI controls. Hope I misreading something or this is a limitation of the Beta that will go away

Comments have been disabled for this content.