Friday, April 11, 2008

Silverlight 2: Custom Controls vs. User Controls

Silverlight_Logo_thumb In my first post on Silverlight 2 I concentrated on how to use User Controls in a Silverlight application.  Since I started writing this post, Scott Guthrie and numerous other developers have also written posts on User Controls.  One thing neither of them cover though is when to use them.  With most technologies there are numerous way to accomplish many tasks, Silverlight is certainly no exception and one example of this comes in the form of User Control vs. Custom Control. 

This post is different than my other Silverlight posts as I'm not showing any code and don't have a cool example to talk about.  This post is meant to be more of a discussion on the differences between User Controls and Custom Controls as well as some guidance on when to use one over the other.  Much of what I'm writing here is just opinion though so if you have a different though or if you find something that I have completely wrong please comment.

Definition

First off let me say that I haven't used Custom Controls much yet so that may sway me a little but I'll try and be open minded.  I'll also say though that it does appear that creating a custom control in Silverlight 2 is significantly easier than creating a custom control in ASP.NET.  Much Easier.

Custom Controls and User Controls both accomplish many of the same goals although in different ways.  It seems to me that this question is nearly the same in Silverlight as it is in ASP.NET, and I suspect with much the same answer.

User Controls

The Silverlight documentation gives two reasons for creating a User Control:

  1. To separate functionality into smaller, manageable pieces of logic that can be created independently from an application and other controls.
  2. To group related controls that can be used more than once in an application.

In practice, user controls are used extensively for both of the reason listed.  One of the great things about them in the ASP.NET world, and now in also in the Silverlight domain, is the ease with which they can be created and reused.

Custom Controls

Custom controls can be loosely defined as creating a control that is based on (i.e. derived from) an existing control and extends its functionality in some way.  Some reason they may be built are to add a capability not included in the base controls, make a company specific version of a control or to group several controls together to perform a specific function.  This last version, grouping several controls to perform a specific function, where the big overlap with User Controls occurs.

One other advantage of custom controls is that since they are compiled into a .dll, they can be reused in multiple Silverlight applications where a User Control is limited to the application in which it is created.

Scenario

While I was working on a new Silverlight 2 project a few weeks ago I had this scenario:

I want multiple blocks to have the same base behavior, such as being resizable, moveable and a similar look/feel.  However, I wanted the contents of these blocks to be different.

With the custom control vs. user control question I went to what is becoming an incredible resource when you are looking for advice but not big text references: twitter.  I happened to know that at least three recognized Silverlight experts (TheADOGuy, LBugnion and WynApse) were on twitter at that moment and that they were following me so I sent a question which resulted in the following conversation (minor editing for clarity):

johnnystock SL2 gurus: If I want to make a custom container object to handle things like drag/drop, look/feel etc. should it be user or custom control?

LBugnion @johnnystock Does your container have an intrisic look&feel, or is it going to change its look often?

TheADOGuy @johnnystock I suggest you derive a custom control from "Panel" but not knowing all your req's that might not be perfect

johnnystock @LBugnion Look/feel will be same for all instances

johnnystock @TheADOGuy Is there a SL2 panel? I was thinking of deriving from Canvas

LBugnion @johnnystock I use UserControls when the look&feel of my control is more or less similar (changes can be handled by styles)

LBugnion @johnnystock and CustomControl for truly lookless controls, where L&F changes a lot depending where they're used

LBugnion @johnnystock That said, the sugestion to make a custom Panel sounds pretty good!

johnnystock @LBugnion That's what I like to hear as personally I find User Controls easier than custom controls :)

LBugnion @johnnystock If you check MIX sessions, Robbie Ingebretsen shows how to create a custom WrapPanel. A good start for what you do

LBugnion @johnnystock Custom Controls are harder to understand, but flexibler to use.

johnnystock @LBugnion cool, thanks for the tips and I'll check tat session out

LBugnion @johnnystock but I do a lot with UserControls too.

TheADOGuy @johnnystock Yes, its the abstract class under all the containers...look at the class def of Canvas in the .chm...

LBugnion @johnnystock The session is Nerd + Art, around 00:46:00

From the above discussion it doesn't really look like there is always a clear cut line on when one type of control is better than the other.  Well, I think there are cases where custom controls are clearly correct, and cases where user controls are clearly right, but there is also a quite large overlapping gray area.  The gray area is seems mostly populated by container controls as well.  It seems like developer preference definitely plays a major part in the decision when in the gray area. 

For what I'm trying to accomplish I will probably be using both.  The functionality will be broken into user controls but the container that houses that user control will be a custom control.  In fact, the only reason I'll be using user controls at all is to reduce clutter and make multi-person development easier as the functionality will not likely be reused.  In my opinion those are valid reasons to use a user control, even though they are not the stated purpose of them.

Conclusion

I am by no means an expert on custom controls but I do have a lot of experience with User Controls and for me I don't know that there is a simple line to choose between here.  Personally I use something like this to help make the decision:

  1. Will this control be used in multiple applications? - probably Custom Control
  2. Is there a base class that has the majority of the functionality needed? - probably Custom Control
  3. Is rapid development a factor? - probably User Control
  4. Am I building it or just specing it out? - probably User Control if I'm building
  5. What am I more comfortable coding myself? - User Controls

Does anyone else have any criteria they use?  I'd love to hear feedback on your preferences as well.

 

UPDATE: Laurent Bugnion has posted a nice article explaining how to bundle a Silverlight User Control in an assembly to use across applications.

Digg!   kick it on DotNetKicks.com

34 comments:

Laurent Bugnion said...

Hi John,

I like your article. In Silverlight like in WPF (like in ASP.NET :), choosing a Custom Control or a User Control is often a matter of preference, as you write.

Interestingly, in ASP.NET I really prefer Custom Controls because I like to have total control over my HTML code (I am anal this way :) but in WPF I prefer User Controls. Go figure. In Silverlight, I didn't quite decide yet. I like the new control model in Silverlight better than the WPF one (read about the gurus' (and good friends) controversy about it, Robbie Ingebretsen, Nathan Dunlap and Dr WPF all expressed their opinion on their blog. I happen to think a lot like Robbie (no wonder since he is also an integrator).

I just wanted to point out that you can also use UserControls in Silverlight even if they are located in another assembly. I will write a blog article showing how later, can't really type too well into here. I'll let you know when it's ready.

Generally speaking, and though the border is thin, you want to choose a CustomControl when it has to be completely lookless, and a UserControl when you want to have some control over the look&feel. Note however that Dr WPF considers that Silverlight Custom Controls, with the new model, are not really lookless anymore...

Friendly greetings,
Laurent

Yuriy Krylov said...

Hey John,

Great post1. With RC0 out, I also took a stab at refining the difference between Custom Controls and User Control.

I've published a Tutorial here: http://e2pt0.blogspot.com/2008/09/silverlight-rc0-custom-controls-appxaml_3894.html

Your thoughts are appreciated!

hjkl said...

Joy in warcraft leveling living comes wow lvl from having wow lvl fine emotions,wow power level trusting them,power leveling giving them power leveling the freedom of wrath of the lich king power leveling a bird in the open.wlk power leveling Joy in living can age of conan gold never be assumed as a pose,or put on from guildwars gold the outside as a mask. People who have this joy don not need maple story mesos to talk about it; they radiate it. wow gold They just live out their joy and let wow power leveling it splash its sunlight and glow into other lives as naturally as bird sings.

dfous said...

Bon marche de Dofus Kamas.achat de dofus.le prix moins cher.nous vendons dofus,or de Wakfu. 24/7 appui-en-ligne et livraison rapide.Wakfu Kamas
china: chinaserving

peter said...

Aftersex toysseries,asex shopof,boardadult toysdetermined,companyadult shoppast,Yahoo'ssexy lingerieweek,meetingsvibratorperson,decisionadult productsbelow,anystrap onshare,overadultshopadvantage,coulddildooffer,theMalaysia sex toysregulators,tryingSingapore sex toysdigging,massivelysex toy$31,thatCondomsaid,takeoverParadise sex toys shopbattle

peter said...

成人情趣取,的情人情趣方,勞情趣商品露,她情趣心,野情趣內衣奴,美人情趣潤滑液露,邊無線跳蛋人,錢充氣娃娃待,聞跳蛋戰,名按摩棒服務,保守逼真老二自,願SM情趣財,政自慰器當,中天堂遊戲情趣用品講,出角色扮演服對,其成人情趣商品他,檔自慰用品切,爾後庭棒西,經情人禮品營,一情趣精品高,

lady said...

KABUL, Afghanistan — Tainted by ed hardy mens clothing
a flawed election and ed hardy womens shoes
allegations of high-level corruption in his regime, ed hardy mens shoes
President Hamid Karzai ed hardy mens longsleeve
was inaugurated Thursday for a second term, ed hardy mens jackets
saying the Afghan Army should assume full control of the country’s security within five years. Ed Hardy chothing
“We will decrease the role of international forces,” ed hardy womens jackets
Mr. Karzai said at a ed hardy bedding
midday ceremony ed hardy hat
held at ed hardy mens jeans
the presidential ed hardy cap
palace in Kabul. ed hardy mens outerwear
“We want our ed hardy belt
security within five ed hardy womens hoodies
years to be entirely ed hardy mens hoodies
within the hands of the Afghan government ed hardy womens outerwear
and led by Afghans.”
The ceremony ed hardy jackets
was the culmination of a fraught ed hardy longsleeve
and chaotic electoral process that began on Aug. ed hardy cap
20 when Afghans went to the polls. ed hardy hat
Mr. Karzai was proclaimed ed hardy bedding
the winner earlier ed hardy belt
this month when his main challenger, christian audigier womens hoodies
Abdullah Abdullah, a former foreign minister, christian audigier hoodieswithdrew from a run-off christian audigier hoodies
after a United Nations-sponsored inquiry christian audigier womens hoodies
found evidence of widespread electoral fraud. ugg boots,
cheap ugg boots,
discount ugg boots,
australia ugg boots,
wholesale ugg boots,

Research Writer said...

Many institutions limit access to their online information. Making this information available will be an asset to all.
Custom Paper Writing

zhuneilixu said...

On New Year's hottest r306c SONY Ericssoncheap cell phones

wholesale
, r306 first win in shape, give a person the feeling of professional and heavy. Its

design clamshell has hidden qualities. Although the low-end market positioning, introduction, SONY

Ericsson R series launched two must let those radio enthusiasts. And there are cheap ones, let the

public mobile phonewholesale of delight

The word "shanzhai" is very popular in China. It is industry phenomenon of imitation, high quality

and low price. Moreover, cell phones are the

representative of them.The global financial crisis led to a significant shri10:25 2009-12-26 nkage

of assets for people. "china wholesale" demonstrate the

might. most of them would like buy the cheap cell phonesnow .

Through google search engine, when you put in "discount cell
phones", you will find more than 15,000 pieces of related information.Cell phone china has been concerned in the world. Many

international sellers can get a considerable profit by ways of wholesale cell phones from China and switch selling. So it is a very

good job on cell phones wholesale in the current cosplay costumes
Anothre set of ralph lauren polo in three colors. Ralph Lauren Polo Shirts come with a graduation of colors on the chest. The new shiki Cheap polo shirts logo is on the chest. Comes in all layres and can be worned tucked in or out Wholesale Polo Shirts -50% OFF.
Also comes with sculpted collar and arm cuffs.Flat knit collar, Contrast placket and half moon, Mothre-of-pearl buttons and tennis tail, Soft double knit piqué,100% cotton ralph lauren polo shirts. If you lend your embroidrere a sample cheapralph lauren polos that will help you get the closest match to the original embroidreed design. The artwork you provide will sreve as a template for your embroidrey set-up but discount ralph lauren polos can't be used to identify some stitch types, cheap polo shirts Cheap Polo Shirtsgive precise sizing of embroidreed elements and show thread polo clothing colors.
Wholesale Polo Shirts
Ralph Lauren Polo Shirts
Discount Ralph Lauren Polos

zhuneilixu said...

The cold winter, does not seem too for wedding. Most recently, the cold one after another, hangzhou air temperature pelter, let many wedding in late November bride is due a single wear gauze or dress, will feel cold, wear too much and feel very bloated. For the bride, the winter is the biggest test how wedding in temperature and balance between poise.

Don't be too upset, actually this season only fees cheap Wedding Dresses, marriage can create a different character "winter wedding", also more memorable.

You can use the glittering and translucent white fairy tale, cheap cell phones
,the artistic conception to dress up oneself's wedding, choose blue, green, white ice cold tonal, decorous atmosphere to create beautiful, Can borrow snow machine and bubble machine build indoor romantic atmosphere, snowflake, feathers, Christmas tree,cheap cocktail dresses, even is the element such as silver crystal, can add to your winter wedding dreamy colour, cheap jewelryyou can even in a pile of snowman YingBinChu lovely, guests, we must take it and will soon be well.

yanran said...

Your blog is wonderful, I like it very much, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do?
polo t shirts women
polo t shirts on sale
polo t shirts for women
polo shirts on sale
polo shirts men
men's polo shirt
men polo shirt
mens polo shirts
mens polo shirt
cheap polo shirts
discount polo shirts
men's polo shirts
women's polo shirts
cheap tennis racket
discount tennis racket
prince tennis racquet
head tennis rackets
wilson tennis racket
babolat tennis racquet

virstock.com said...

Dofus Kamas|Prix Moins Cher Dofus Kamas|Kamas par allopass|Dofus kamas audiotel|Dofus kamas par telephone sur Virstock.com

Meilleur prix dofus kamas stock de dofus kamas

Prix moins cher dofus kamas
vente dofus kamas sur www.virstock.com

Kamas par allopass sur dofus kamas

Dofus kamas par telephone sur dofus kamas

Dofus kamas audiotel sur dofus kamas

http://www.virstock.com/jsp/comments.jsp dofus kamas vente

http://www.virstock.com

Nicole C said...

buy viagra
viagra online
generic viagra

King Bayern Munich said...

We supply many styles of sofas,such as living-room-sofa, Modern leather sofa . soft sofa. Lounge-sofa .
e supply all kinds of stone product,such as china tombstones, Modern-stone-sculpture, paving-stone Glazed-Vitrified-Tiles

SEO Services Consultants said...

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck! Web Design Company

nedox said...

Wonderful information, I will save this and show it to my friend, she is huge fan of this. It's been a pleasure to read your post.
Hannah from SheepArcade
If you like to play games, visit sheep arcade and play arcade games and much more free games.

alice said...

Helo, your blog is really good, I like it very much!By the way, if you like nike chaussures tn you can come here to have a look!
ugg outlet
uggs outlet
ugg classic
ugg classic boots
ugg online
ugg boots
cheap ugg boots
discount ugg boots
australia ugg boots
wholesale ugg boots
sheepskin ugg boots
ugg boots 5815
ugg boots size 9
ugg snowboots
womens ugg boots
classic tall ugg boots
short ugg boots
new ugg boots
winter ugg boots
ugg boots outlet

angelina said...

Super job ! Your webpage has provided me all the particulars I expected .
locksmith fort worth texas
Nashville TN Locksmith
Locksmith San Mateo
Milpitas locksmith
Locksmith Milpitas CA
Locksmith Milpitas CA
Locksmith Milpitas CA
pembroke pines locksmith
pembroke pines locksmith
Locksmith Hialeah FL
Locksmith Mesquite
Locksmith Mesquite
locksmith Aventura FL
pembroke pines locksmith
fort worth locksmith
mesquite locksmiths
locksmith miami beach
locksmith miami beach
locksmith fort worth texas
mesquite locksmiths
mesquite locksmiths
locksmith miami beach
locksmith miami beach fl
locksmith miami beach
mesquite locksmiths
locksmith hialeah fl

Kelsi said...

dsquareddsquared
dsquared shoesdsquared shoes
dsquared shoes 2011dsquared shoes 2011
dsquared jeans womendsquared jeans women
dsquared t shirtsdsquared t shirts
dsquared jeans mendsquared jeans men
dsquared hoodiesdsquared hoodies
dsquared beltsdsquared belts
asics shoes saleasics shoes sale
asics shoesasics shoes
asics running shoesasics running shoes
asics mexico 66asics mexico 66
onitsuka kanuchionitsuka kanuchi
timberland bootstimberland boots
christian louboutin shoeschristian louboutin shoes
karen millen dresseskaren millen dresses
nike air max plusnike air max plus
maillot de football 2011maillot de football 2011

vibrams said...

The christian louboutin heels is designed for the ladies. Since the pumps was born, the ladies life become colorful. The christian louboutin evening pumps are the god's masterwork. Who invited thechristian louboutin pumps? Seldom people knew, but I think every lady would be grateful for him. Among the countless pumps, the christian louboutin peep toe is the most outstanding ones. The elegant pattern, the delicate style all mold the ladies perfect leg profile. Flowers in the spring of 2011 creeping, up from hair to clothes continue to footwear, have had a brilliant up. In such a glamor, spring and summer flowers now here. Romance is a woman's mood, exquisite flowers just right of expression in our gestures, the woman, how can we not love the romantic temperament so that they distributed the flowers do? 2011 flowers bloom will enjoy different poses! The Christian Louboutin 2011 Sandals also can adds the hright of the ladies, it bring surprise to the short lady. Especially the red sole of the louboutin heels, magic and sexy, many ladies are crazy. The red sole, the first feature of the Christian Louboutin stroe.

truddy said...

Louboutins shoes are regarded as as since the symbol of sexy and classy.Christian Louboutin names after a famous shoes designer who launched his line of high-end women's shoes. Now come to Louboutin UK store! We will change you into a gorgeous girl! Here provides Discount Christian Louboutin Sandals,Cheap Christian Louboutin,Louboutin Mens Collection and so on.The unique and well-Designed shoes favored by the world, signed with the Christian Louboutin red soles of the mark, giving high heels and covetable accessories, system pumps and elegant luxury Christian Louboutin clutch has to be available almost all fashion only. We now provide Christian Louboutin shoes with free shipping and save 60% off! Hurry up! Christian Louboutin UK store is your first choice!

vibrams said...

The christian louboutin store was designed for the ladies. Since the louboutin heelswas born, the ladies life become colorful.The elegant pattern, the delicate style all mold the ladies perfect leg profile. The christian louboutin evening pumps are the god's masterwork. Who invited the christian louboutin pumps? Seldom people knew, but I think every lady would be grateful for him. Among the countless pumps, the christian louboutin peep toe is the most outstanding ones. Flowers in the spring of 2011 creeping, up from hair to clothes continue to footwear, have had a brilliant up. In such a glamor, spring and summer flowers now here. Romance is a woman's mood, exquisite flowers just right of expression in our gestures, the woman, how can we not love the romantic temperament so that they distributed the flowers do? 2011 flowers bloom will enjoy different poses! The Christian Louboutin 2011 Sandals also can adds the hright of the ladies, it bring surprise to the short lady. Especially the red sole of the louboutin heels, magic and sexy, many ladies are crazy. The red sole, the first feature of the Christian Louboutin heels.

jelish said...

Christian Louboutin Outlet Online Store offer 2011 new-style Christian Louboutin Sale Outlet online store.We will provide you with all kinds of CL.The Christian Louboutin Ankle Boots serve different functions and keep your feet stylish and warm,Christian Louboutin High Heels can always show our body in the best charming way, making her legs look as long as possible.Christian Louboutin New Style are the best choice for you to choose the brand, especially you want to keep steps to the fashion world.Christian Louboutin Peep Toes that are considered as classic due to the fact they are comfortable.Buy cheap Christian Louboutin Outlet Online shoes, get your favorite.
http://www.christianlouboutinoutletonline.org

jelish said...

You wish for getting to create people nowadays worried about women? can you need a awesome coloring as women? We are Louboutin 2011store. we are able to provide you using a broad wide variety of Sale Louboutin. For example:Christian Louboutin Slingbacks,Christian Louboutin Peep Toe,Christian Louboutin Evenings,Christian Louboutin Pumps. andChristian Louboutin Mensis a very distinctive design, its design reflects its style. You put on it, that means you have its style.You put on it, that means you have its style.They are astonishingly psychological color. Please do not pass up an superb chance.
http://www.sale-louboutin-shoes.us

Image said...

Tks very much for post:



I like it and hope that you continue posting.



Let me show other source that may be good for community.

I love Polo logo shirts...........

LauraStarBene said...

Nice post! Thanks for sharing!
Comprare Valium

LauraStarBene said...

Nice post! Thanks for sharing!
Comprare Valium

abercrombiefitch said...

Thank you for your article to share with us, our online store Nike Outlets, have a good product Nike Air Max shoes, interested welcome to come in and see 2011 Cheap Nike Air Max Online Store, Hot products: Mens Nike Air Presto 2009 Gray Red Training Shoes. Best Nike Shoes Where can you buy UGG Outlet Store?.

gud uk said...

Nike Shoes Us Max 87 attribute a awesome grey bottom coloring having a bright Nike swoosh and hyper blue accents along the lone within the sneaker and heel. Also on this pair they kept their mesh toe box layout for additional comfort and breathability. Nike generally introduces numerous designs of operating footwear for numerous Womens Nike Air Max 90 groups. No make any difference you are teens or adults who like being in action using the sports activities trends, you can just Womens Nike Air Max 95 locate probably the most attractive oxygen max footwear to concur along with your censorious taste. Now right here would be the warm marketing ladies Nike oxygen Max 90 operating footwear as properly as the males Nike oxygen Max 90 footwear to match your needs at shoes-dream. com.

gud uk said...

Nike Shoes Us Max 87 attribute a awesome grey bottom coloring having a bright Nike swoosh and hyper blue accents along the lone within the sneaker and heel. Also on this pair they kept their mesh toe box layout for additional comfort and breathability. Nike generally introduces numerous designs of operating footwear for numerous Womens Nike Air Max 90 groups. No make any difference you are teens or adults who like being in action using the sports activities trends, you can just Womens Nike Air Max 95 locate probably the most attractive oxygen max footwear to concur along with your censorious taste. Now right here would be the warm marketing ladies Nike oxygen Max 90 operating footwear as properly as the males Nike oxygen Max 90 footwear to match your needs at shoes-dream. com.

baele said...

So how is the Nike mercurial soccer cleats changed? the original Nike Speed boot!New products Nike Football Boots for us.the new Vapor football boots have undergone the same new paint work as the Nike Mercurial Superfly boots and now feature the Nike Football Boots updated asymmetric.

Latest nike shoes said...

Wonderful article ah well. Content is real attractive. The way to bring you good news: This Nike soccer cleats ultra vibrant...The Nike mercurial soccer cleats has a huge army of fans across the globe, and if you're one of them we know you love them to be bright, flashy and in-your-face colours. Checking out these New nike soccer shoes versions, part of Nike's Fall seasonal releases, we're sure you're going to love these too, they combine Laser technology and Nike Mercurial Vapor Superfly with the Vapor series!especially once they start appearing en masse on pitch. You can click "VIEW MORE" for more detailed pictures. New levels of performance after Nike Football Cleats new levels of performance after.

London Crumpet said...

London escorts directory London Crumpet is created to expose Independent escorts and escort agencies in London. Everybody can post their advert on this directory for FREE.

Learn Chinese language on hanbridgemandarin said...

All Hanbridge instructors are accredited language teachers, native speakers of Mandarin, and have obtained a Bachelor's or Master's Degree. in language. All have standard Mandarin pronunciation and have completed Hanbridge's rigorous training program.Most importantly, they are committed to and enthusiastic about teaching and have a passion to help people learn to speak Mandarin and learn about Chinese culture.



More Chinese learning tags : Mandarin Online Course | study Chinese online | learning to speak Chinese