THE EXPERT’S VOICE
®IN SILVERLIGHT
Beginning
Silverlight 4
in
C#
Robert Lair
Learn to build state-of-the-art Silverlight
applications quickly and easily
Beginning Silverlight 4
in C#
■ ■ ■
Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans,
[email protected],orvisitwww.springeronline.com.
Forinformationontranslations,pleasee-mail[email protected],orvisitwww.apress.com.
ApressandfriendsofEDbooksmaybepurchasedinbulkforacademic,corporate,orpromotionaluse. eBookversionsandlicensesarealsoavailableformosttitles.Formoreinformation,referenceour SpecialBulkSales–eBookLicensingwebpageatwww.apress.com/info/bulksales.
Theinformationinthisbookisdistributedonan“asis”basis,withoutwarranty.Althoughevery precautionhasbeentakeninthepreparationofthiswork,neithertheauthor(s)norApressshallhave anyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecaused directlyorindirectlybytheinformationcontainedinthiswork.
Contents at a Glance
AbouttheAuthor...xv
AbouttheTechnicalReviewer...xvi
Acknowledgments...xvii
Introduction...xviii
■
Chapter1:WelcometoSilverlight4...1
■
Chapter2:IntroductiontoVisualStudio2010...13
■
Chapter3:LayoutManagementinSilverlight...29
■
Chapter4:SilverlightControls...59
■
Chapter5:DataBindingandSilverlightListControls...87
■
Chapter6:SilverlightToolkit...123
■
Chapter7:DataAccessandNetworking...149
■
Chapter8:NavigationFramework...165
■
Chapter9:IsolatedStorageinSilverlight...193
■
Chapter10:SystemIntegrationandDeviceSupport...223
■
Chapter11:IntroductiontoExpressionBlend...245
■
Chapter12:StylinginSilverlight...263
■
Chapter13:TransformationsandAnimation...297
■ CONTENTSATAGLANCE
■
Chapter15:PrintinginSilverlight...343
■
Chapter16:Deployment...359
Contents
AbouttheAuthor...xv
AbouttheTechnicalReviewer...xvi
Acknowledgments...xvii
Introduction...xviii
■
Chapter1:WelcometoSilverlight4...1
TheEvolutionoftheUserInterface...1
RichInternetApplicationSolutions...4
WhatIsSilverlight?...4
BenefitsofSilverlight...5
Cross-Platform/Cross-BrowserSupport...6
Cross-PlatformVersionofthe.NETFramework...6
UseofFamiliarTechnologies...7
SmallRuntimeandSimpleDeployment...7
TheSilverlightDevelopmentEnvironment...8
NewFeaturesinSilverlight4...10
ImprovedPerformance...11
■ CONTENTS
■
Chapter2:IntroductiontoVisualStudio2010...13
WhatIsVisualStudio?...13
What’sNewinVisualStudio2010?...14
SupportforMultipleMonitors...14
ZoomSupportforSourceEditor...15
ExtensionManager...21
BuildingYourFirstSilverlightApplicationinVisualStudio...22
TryItOut:HelloWorldinSilverlight4...22
HostingYourSilverlightApplication:WebSiteorWebApplication?...26
Summary...28
■
Chapter3:LayoutManagementinSilverlight...29
LayoutManagement...29
TheCanvasPanel...30
TryItOut:UsingtheCanvasPanel...31
FillingtheEntireBrowserWindowwithYourApplication...35
TheStackPanelControl...36
TryItOut:UsingtheStackPanelControl...36
TryItOut:NestingStackPanelControls...39
TheGridControl...41
TryItOut:UsingtheGridControl...42
TryItOut:NestingaGridandSpanningaColumn...46
TheWrapPanelControl...50
TryItOut:UsingtheWrapPanelControl...51
TheDockPanelControl...55
TryItOut:UsingtheDockPanelControl...55
■
Chapter4:SilverlightControls...59
SettingControlProperties...59
AttributeSyntax...59
ElementSyntax...60
Type-Converter-EnabledAttributes...60
AttachedProperties...60
NestingControlsWithinControls...61
HandlingEventsinSilverlight...62
TryItOut:DeclaringanEventinXAML...63
TryItOut:DeclaringanEventHandlerinManagedCode...67
TheBorderControl...71
UserInputControls...75
TryItOut:WorkingwiththeTextBoxControl...75
TryItOut:WorkingwiththeRadioButtonandCheckBoxControls...79
ExtendedControls...82
AddinganExtendedControl...82
TryItOut:UsingtheGridSplitter...83
Summary...86
■
Chapter5:DataBindingandSilverlightListControls...87
DataBinding...87
TheBindingClass...88
TryItOut:SimpleDataBindinginSilverlight...88
ElementtoElementBinding...97
TryItOut:ElementtoElementBinding...97
TheDataGridControl...99
■ CONTENTS
TheListBoxControl...114
DefaultandCustomListBoxItems...114
TryItOut:BuildingaListBoxwithCustomContent...116
NewDataBindingFeaturesinSilverlight4...118
DataBindingandStringFormatting...118
TargetNullValueandFallBackValueExtensions...120
Summary...121
■
Chapter6:SilverlightToolkit...123
OverviewoftheSilverlightToolkit...123
InstallingtheToolkit...125
ToolkitControls...126
Accordion...126
TryItOut:WorkingwiththeAccordionControl...127
AutoCompleteBox...132
TabControl...134
ViewBox...135
ModalWindows...137
TryItOut:UsingtheModalChildWindow...138
Summary...148
■
Chapter7:DataAccessandNetworking...149
DataAccessinSilverlightApplications...149
AccessingDataThroughWebServices...150
TryItOut:AccessingDataThroughaWCFService...150
AccessingServicesfromOtherDomains...161
AccessingDataThroughSockets...162
■
Chapter8:NavigationFramework...165
FrameandPageObject...165
TryItOut:CreatingaSilverlightNavigationApplication...166
BenefitsoftheNavigationFramework...175
DeepLinking...175
TheNavigationServiceObject...176
TryitOut:UsingtheNavigationServiceObject...177
PassingDatatoNavigationPages...179
TryitOut:PassingDatatoNavigationPages...179
UriMapping...183
TryitOut:UriMappingandtheNavigationFramework...183
SilverlightNavigationApplicationTemplate...186
TryitOut:UsingtheSilverlightNavigationApplicationTemplate...186
UsingMultipleFrames...190
TryitOut:UsingMultipleFrames...190
Summary...192
■
Chapter9:IsolatedStorageinSilverlight...193
WorkingwithIsolatedStorage...193
UsingtheIsolatedStorageAPI...194
TryItOut:CreatingaFileExplorerforIsolatedStorage...196
ManagingIsolatedStorage...218
ViewingandClearingIsolatedStorage...218
TryItOut:IncreasingtheIsolatedStorageQuota...219
■ CONTENTS
■
Chapter10:SystemIntegrationandDeviceSupport...223
Notification(Toast)API...223
TryItOut:ImplementingToastNotifications....223
Webcam/MicrophoneAccess...229
TryItOut:AccessingaUser’sWebCameraandMicrophone...230
WorkingwithCapturedStreams...235
COMInteroperability...235
TryItOut:ExecutinganEXE...236
DroppingFilesonaSilverlightApplication...240
DropEvent...240
TryItOut:EnablinganApplicationAsaDropTarget...240
Summary...243
■
Chapter11:IntroductiontoExpressionBlend...245
KeyFeaturesinExpressionBlend...245
VisualXAMLEditor...246
VisualStudio2010Integration...246
Split-ViewMode...246
VisualStateManagerandTemplateEditingSupport...247
World-ClassTimeline...247
TryItOut:WorkingwithProjectsinExpressionBlend...248
ExploringtheWorkspace...252
Toolbox...252
ProjectPanel...254
PropertiesPanel...254
LayingOutanApplicationwithExpressionBlend...255
WorkingwiththeGridControlinExpressionBlend...255
TryItOut:EditingaLayoutGridwithExpressionBlend...256
Summary...262
■
Chapter12:StylinginSilverlight...263
InlineProperties...263
TryItOut:SettingInlinePropertieswithVisualStudio...263
TryItOut:SettingInlinePropertieswithExpressionBlend...271
SilverlightStyles...280
TryItOut:UsingStylesAsStaticResources...281
DefiningStylesattheApplicationLevel...289
MergedResourceDictionaries...290
SilverlightStyleHierarchy...292
InheritingStylesUsingBasedOn...293
ImplicitStyles...294
Summary...296
■
Chapter13:TransformationsandAnimation...297
IntroductiontoSilverlightAnimation...297
SilverlightStoryboards...298
TypesofAnimationsinSilverlight...299
ProgrammaticallyControllingAnimations...301
UsingExpressionBlendtoCreateAnimations...303
ViewingaStoryboardintheExpressionBlendTimeline...304
TryItOut:CreatinganAnimationwithExpressionBlend...304
CreatingTransformationsinSilverlight...312
■ CONTENTS
■
Chapter14:CustomControls...321
WhentoWriteCustomControls...321
SilverlightControlModel...322
PartsandStatesModel...322
DependencyProperties...323
CreatingCustomControlsinSilverlight...324
ImplementingCustomFunctionality...324
TryItOut:BuildingaCustomControl...324
Summary...341
■
Chapter15:PrintinginSilverlight...343
ThePrintingAPI...343
TryItOut:ImplementingSimplePrinting...343
PrintingCustomContent...351
TryItOut:ImplementingaCustomPrint...351
AdditionalPrintingCustomization...354
TryItOut:HandlingtheBeginPrintandEndPrintEvents...354
Summary...357
■
Chapter16:Deployment...359
DeployingSilverlightApplications...359
XAPFiles...359
HostingSilverlightContent...359
ApplicationLibraryCaching...360
TryItOut:ExploringAssemblyCaching...361
OutofBrowserSupport...365
CustomizingtheInstallApplicationDialog...367
OutofBrowserAPI...369
RemovingInstalledApplications...370
ElevatedTrustApplications...371
Summary...374
About the Author
■RobertLairbeganworkingwith.NETtechnologiesbeforeits
alpha,andhebuilttheoriginalIBuySpye-commerceandportal applicationsMicrosoftusedtointroduceASP.NETtothe developmentcommunity.Robertspecializesinanumberof technologies,includingSilverlight,mainframemodernizationto .NET,ASP.NETcustomapplicationdevelopment,SharePoint developmentandintegration,andmanyothers.Today,Robert worksasthedevelopmentmanageratT3Technologies (http://www.t3t.com),acompanythatoffersmainframe
alternativesontheWindowsplatform.Hehaswrittenmanybooks andmagazinearticles,includingBeginningSilverlight3(Apress, 2009),andhasalsobeenaspeakeratanumberof.NETtechnical conferences.Followhimontwitterathttp://www.twitter. com/robertlairandonthewebathttp://www.robertlair.net.
About the Technical Reviewer
■FabioClaudioFerracchiatiisaseniorconsultantandanalyst/developerofMicrosofttechnologies
whoworksfortheItalianbranchofBrainForce(http://www.brainforce.it).HeisbothaMicrosoft CertifiedSolutionDeveloperandaMicrosoftCertifiedApplicationDeveloperfor.NET,aswellasa MicrosoftCertifiedProfessional.Fabioisalsoaprolificauthorandtechnicalreviewer.Overthepast10 years,he’swrittenarticlesforseveralinternationalmagazinesandcoauthoredmorethan10booksona varietyofcomputertopics.
Acknowledgments
IwouldliketothankthemanypeopleatApresswhomadethisbookhappen—especiallyDebraKelly, EwanBuckingham,DominicShakeshaft,andFabioClaudioFerracchiati.Withoutallofyourhardwork, thisbookwouldneverhavecomeabout.Thankyouall!
Thanksalsotomylovingwife,Debi,forherpatiencewhileIwrotethisbook.ToooftenIlefther alonetotakecareofoursonandtokeepourhousemaintained.Thankyouforbeingsuchawonderful wife.Iwouldalsoliketothankmyson,Max,forunderstandingwhenDaddycouldn’tplaybecausehe hadtowrite.
Iwouldalsoliketothankourgreatneighbors,whohaveprovidedmewithgreatfriendshipand support.Wehavebeenblessedwithanawesomestreetfilledwithwonderfulpeople.Inparticular,I’d liketothankMikeandConnieVandermarkforprovidingthevolleyballcourtweallenjoysomuch, GeorgeMullerforhostingSci-FiFridayeveryweek,andJimandStephanieSurianofornotonlybeing greatneighborsbutalsoincrediblefriendstomyfamily.
Finally,Iwanttogiveashoutouttomyonlinegamingfriends,KristenLudec,SamWrich,andSam Transue.Thoughweonlyknoweachotheronline,IvalueyourfriendshipandIthankyouforyour companionshipandsupportoverthelastfewyears.
Introduction
TherearemanywaystolearnanewtechnologysuchasSilverlight.Forstarters,Microsofthasgotten betterandbetterwiththedocumentationitreleaseswithitsprogrammingtechnologies,andemployee blogsandtechnologysitessuchashttp://www.silverlight.nethelpbysupplementingthat
documentation.Moreover,youcangetinformationatanumberofwidelyusedforumswheremany expertsparticipate,and,ofcourse,youcanalwayspurchasetrainingifyouhavethecashflowtojustify it.Whileallofthesearegreatoptions,manypeoplestillliketopurchaseabookonthetechnology.But withsomanybooksonthemarket,howdoyouknowwhichisbest?
Myownphilosophyaboutlearninganewtechnologyisthatthereisnobetterwaythantoactually tryitoutforyourself.That’swhyIwroteBeginningSilverlight4inC# asanumberofstep-by-step,walk-throughtutorialsthatgiveyouhands-onexperiencewiththedifferenttopicsandgetyoustarted developingSilverlightapplicationsonyourown.
WhoShouldReadThisBook
ThisbookisforapplicationdeveloperswhowanttogetstartedwithSilverlight4.Itassumesyouhave someexperiencedevelopingapplicationsusingtechnologiesrelatedtoMicrosoft’sVisualBasic,ASP,or .NET,andhaveworkedwithMicrosoftVisualStudio.YoushouldbefamiliarwithJavaScript,C#,and XML.
HowThisBookIsOrganized
EachchapterfocusesonaparticularareaofSilverlightandcontainsoneormore“TryItOut”exercises thatletyouapplywhatyou’velearned.Here’sbriefguidetowhatyou’llfindineachchapter:
• Chapter1,“WelcometoSilverlight4,”introducesyoutoRIAsandSilverlight. You’llalsolearnaboutthetoolsusedindevelopingSilverlight-enabled applications.
• Chapter2,“IntroductiontoVisualStudio2010,”presentsVisualStudio2010and theimportantnewfeaturesitoffers.Inthischapter,you’llbuildyourfirst Silverlightapplication.
C H A P T E R 1
■ ■ ■
Welcome to Silverlight 4
ThischapterintroducesSilverlight,aMicrosoftcross-browser,cross-platformplug-inthatallowsyouto createrichinteractive(orInternet)applications(RIAs)fortheWeb.Itbeginswithabrieflookatthe evolutionofuserinterfaces,andthenprovidesanoverviewofSilverlight.You’lllearnhowSilverlightfits intoRIAsolutions,thebenefitsitbringstodevelopers,andthetoolsinvolvedindevelopingSilverlight-enabledapplications.
TheEvolutionoftheUserInterface
Softwareuserinterfacesareconstantlyevolvingandimproving.IrememberbackwhenIwasstill workingwithanearlyversionofWindowsandlookingatMacOSwithenvy.Then,Irememberseeing Linuxsystemswithradicalnewdesktopinterfaces.Morerecently,Ifoundmyselflookingagainatthe MacOSXDock(seeFigure1-1)andwantingthatformyWindowsXPmachine—tothepointwhereI purchasedaproductthatmimickedit.IwasdedicatedtoWindowsthroughitall,butIwasenviousof someoftheuserexperiencesthedifferentenvironmentsoffered.
Figure1-1.TheMacOSXDockfeature
TheevolutionoftheuserinterfacecontinuesintheWindowsoperatingsystem.Perhapsthemost prominentdifferencebetweenWindows7andpreviousversionsofWindowsisuserinterface
improvements.Microsoftwasveryintentionalonimprovingtherichnessoftheoperatingsystem.One exampleisthenewtaskbar,wherelargeiconsreplacethetextdescriptionsandwhentheuserplacesthe cursoroveraniconwilldisplayawindowthumbnail,asshowninFigure1-2.
Figure1-2.Windows7improvedtaskbar
AnotheruserinterfaceimprovementinWindows7istheAeroSnap.Thisfeatureallowsyoutoeasily maximizeyourwindowbydraggingittothetopofthescreen,butitalsoallowsyoutodragthewindow totheleftorrightedgeofthescreeninordertotilethewindowto50%oftheleftorrightsideofthe screenasshowninFigure1-3.
Figure1-3.Windows7AeroSnapfeature
CHAPTER1■ WELCOMETOSILVERLIGHT4
veryrichexperience,theyhaveverysmallreach.Theapplicationneedstohaveacodebaseforeach targetplatform,andeverymachineneedstohavetheapplicationinstalledandmaintained.
Incontrast,wehavewebapplications,whichareHTML-focusedprogramsdesignedtorunwithina browserandacrossplatforms.FortheMicrosoft-baseddeveloper,thishasrecentlymeantdeveloping withASP.NETandbuildingwebservicestoofferservicesovertheInternet.Thefocusofmostofthelogic andcodehasbeenplacedontheserverforthebenefitofapplicationperformance.Thepricehasbeena pooruserinterface.Theseapplicationshadexcellentreach,buttheywerenotveryrich,asshownin Figure1-4.Betweenthesetwoextremesthereisacleargapbetweenthetechnologies.
Figure1-4.Richandreachapplicationcomparison
Tofillthisgap,anewdevelopmentapproachhassurfaced,asshowninFigure1-5.Thisnew approachistermedRIA(RichInternetApplications),whichisdefinedasawebapplicationthathasthe featuresandfunctionalityfoundintraditionaldesktopapplications.AlthoughthereareanumberofRIA technologies,includingMicrosoft’sSilverlight.
RichInternetApplicationSolutions
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="FirstLookXaml.MainPage" Width="640" Height="480">
<Canvas x:Name="LayoutRoot" Background="White">
CHAPTER1■ WELCOMETOSILVERLIGHT4
Figure1-6showsthiscanvasinMicrosoftExpressionBlend,thedesigntoolusedtoeditandcreate XAMLforSilverlightapplications.YoucanseethatthisXAMLsimplydefinesarectangleonacanvas,as wellasthepropertiesassociatedwiththatrectangle,includingitsname,location,size,color,andborder.
ThissimpleexampleisjustintendedtogiveyouanideaofwhatXAMLlookslike.You’lllearnmore aboutXAMLinupcomingchapters.Fornow,let’scontinuebylookingatthebenefitsofSilverlight.
Figure1-6.AbasicXAMLcanvasinMicrosoftExpressionBlend
BenefitsofSilverlight
Naturally,SilverlightoffersallofthesamebenefitsofRIAs,butthereareafewfeaturesthatsetitapart fromotherRIAsolutions,includingthefollowing:
• Itofferscross-platform/cross-browsersupport.
• Itprovidesacross-platformversionofthe.NETFramework.
• XAMLisatext-basedmarkuplanguage.
• Silverlightusesfamiliartechnologies.
CHAPTER1■ WELCOMETOSILVERLIGHT4
UseofFamiliarTechnologies
Microsoftisverygoodatcreatingtoolsthatmakeapplicationdevelopmenteasy.TheVisualStudio integrateddevelopmentenvironment(IDE)hasbeenaroundforquitesometime,andalthoughnew featuresarecontinuallyaddedtothetool,theenvironmentitselfhasremainedremarkablyconsistent.
Silverlightdevelopmentisnodifferent.AtthecoreofdevelopingSilverlightapplicationsisVisual Studio2010,thelatestversioninVisualStudio’slonghistory.ThisgivesSilverlightadistinctadvantage, asdevelopersdonotneedtolearnhowtouseanewdevelopmentenvironment.
InadditiontoVisualStudio,MicrosofthasasuiteoftoolscalledExpressionStudio.Includedinthis suiteisMicrosoftExpressionBlend,whichisusedtoeditandcreateXAMLforSilverlightapplications. WhileExpressionBlendlookscompletelydifferent,itstillhasmanyofthesameelementsasVisual Studio.Inaddition,ExpressionBlendworksoffofthesameprojectasVisualStudio.Thismeansthatas youmakechangesineachoftheeditors—openingaprojectinVisualStudio,andthenopeningthesame projectinExpressionBlendtoedittheXAML—theeditedfileswillrequesttoberefreshedwhenopened againintheothertool.
SmallRuntimeandSimpleDeployment
SinceSilverlightrequiresthataclientruntimebeinstalledontheclientmachine,itisvitalthatthis runtimehasasmallfootprintanddownloadsquickly.Microsoftworkedveryhardtogettheinstallation sizeassmallaspossible.ThedevelopersclearlysucceededwithSilverlight1.0,asthedownloadsizeisa tiny1MB.ForSilverlight2,however,theyhadaharderchoreaheadofthem,sinceSilverlight2contains itsown.NETFrameworkandobjectlibrary.Microsoftwenttoeach.NETFrameworkteamandallocated itasizetofititsportion.Theendresultisastonishing—Silverlight2isapproximately4MBinsize.In Silverlight4,evenwiththelargeamountofnewfeaturesthathavebeenaddedtotheSilverlightruntime, thefilesizeisstilllessthan6MB.
AsforpushingtheSilverlightruntimeouttoclients,Microsofthasprovidedaveryeasydetection mechanism.IftheclientdoesnothavetheproperSilverlightruntimeinstalled,itwilldisplayalogo, similartotheoneshowninFigure1-7.
Whenusersclicktheiconinthelogo,theSilverlightruntimewillstarttodownload.Oncethe runtimeisfinishedinstalling,theSilverlightapplicationisimmediatelyavailabletotheuser.
TheSilverlightDevelopmentEnvironment
Inthepast,settingupanenvironmenttoworkwithMicrosoft’slatestandgreatesthasbeenrelatively straightforward,typicallyinvolvingonlythesetupofthelatestversionofVisualStudioandthe
appropriatesoftwaredevelopmentkit.However,withSilverlight,thesituationisquiteabitdifferentdue totheintroductionofmanynewtools.Let’slookatthetoolsinvolvedinsettingupaSilverlight4 developmentenvironment.
1. VisualStudio2010:Asnoted,thisisthelatestversionofMicrosoft’sIDE,the successortoVisualStudio2008(seeFigure1-8).ForyourSilverlight
environmentyoushouldinstallVisualStudio2010,whichautomatically installsMicrosoft.NETFramework4.Chapter2coversVisualStudio2010in moredepth.
Figure1-8.MicrosoftVisualStudio2008
CHAPTER1■ WELCOMETOSILVERLIGHT4
• Silverlight4Runtime:Requiredoneverycomputerthatwishestoviewa Silverlight-enabledwebapplication.
• Silverlight4SoftwareDevelopmentKit:ThisSDKisacollectionofsamples, SilverlightQuickStarts,documentation,andcontrolsthatareusedto developSilverlightapplications.
• SilverlightProjectTemplatesforVisualStudio2010:ThisaddstheSilverlight templatesinVisualStudio.Asanexample,itwilladdthetemplatethat enablesyoutocreateaSilverlightprojectfromthe“AddNewProject”in VisualStudio.
3. ExpressionBlend4:ThenextthingtoinstallforyourSilverlightdevelopment environmentisExpressionBlend(seeFigure1-9).ExpressionBlendadesign toolforbuildingXAMLbasedinterfacesincludingWindowsPresentation Foundation(WPF)andSilverlight.ExpressionBlendisnotrequiredfor creatingSilverlightsolutions,butprovidesaricherdesignerthandoesVisual Studio2010.ExpressionBlend4iscoveredindetailinChapter11.
4. Silverlight4Toolkit.TheSilverlightToolkitisanopensourceCodePlexproject whosegoalistodevelopadditionalcontrolsforSilverlightapplications. Controlswithinthetoolkitareassignedastatusthatdescribestheirmaturity ascontrolsandthecontrolsaresupportedbytheopensourcecommunity. YoucandownloadthetoolkitforSilverlight4athttp://www.codeplex.com/ silverlight.TheToolkitisdiscussedinChapter6.
NewFeaturesinSilverlight4
SilverlightcontinuestoevolveandMicrosoftcontinuestoaddnewfeaturestoSilverlightineachversion. TherearemanynewfeaturesintroducedinSilverlight4.Thissectionwillgooversomeofthosenew featuresandwillindicatewherethosefeaturesarediscussedinthisbook.
• ElevatedTrustApplications:InreleasesofSilverlightpriortoversion4,Silverlight applicationswererestrictedtoasandboxanddidnothaveaccesstoaclient’s devicesorharddrive.InSilverlight4developershaveanoptiontocreateelevated trustapplicationsthatwillgainaccesstodevicesontheclientmachineaswellas theclient’sharddrive.ElevatedTrustSilverlightApplicationsarediscussedin Chapter16.
• NewControls:WitheachnewversionofSilverlight,moreandmorecontrolsare added.ThisisnodifferentwithSilverlight4,whichhasaddedanumberofnew controlssuchastheRichTextAreaandViewBoxcontrol.Thesecontrolsare discussedinChapters3to6.
• SystemIntegrationandDeviceSupport:Oneothershort-comingofpastreleasesof Silverlightisthelackofdevicelevelsupport.InSilverlight4,developerscannow accessauser’sattachedwebcameraand/ormicrophonewithjustafewlinesof code.Inadditiontowebcamsandmicrophones,additionalsupportformouse wheelandrightmouseclickhasalsobeenaddedtoSilverlight4.DeviceSupportis discussedinChapter10.
• PrintingSupport:OneofthemostpopularnewfeaturesinSilverlight4isthe addedsupportforclient-sideprinting.Silverlight4includesanextensibleprinting APIthatwillallowdeveloperstoenableclientprintingfromaSilverlight
application.Developerscaneitherprintthecontentsofavisualtreefromwithin theSilverlightapplication,ortheycanconstructacustomvisualtreethatwill allowenduserstoprintcustomizedviewsofdatadirectlyfromSilverlight.
• CustomWindowChrome:OneofthebiggestfeaturesofSilverlightwastheability torunSilverlightapplicationsoutofthebrowser.However,itdidn’ttakelonguntil developerswereimmediatelyrequestingtheabilitytoallowtheiroutofbrowser SilverlightApplicationstoescapethestandardwindowschrome.InSilverlight4 developerscancreatetheirowncustomchromefortheirapplicationssotheir entireapplicationcanhaveaconsistentlook,includingtheapplication’sframe.
CHAPTER1■ WELCOMETOSILVERLIGHT4
• SilverlightasDropTarget:Ifyouareusedtousingdesktopapplications,youare alsoprobablyfamiliarwiththeabilitytodragfilesontotheapplicationtoperform
• NotificationPop-ups(ToastWindowSupport):Attimesitisveryusefultonotify theuserofeventsinyourapplication.Thestandardthathasformedinthe
C H A P T E R 2
■ ■ ■
Introduction to Visual Studio 2010
ThepreviouschaptermentionedthetoolsrequiredtodevelopRIAsthatutilizetheSilverlight
technology.AtthecoreofallofthesetoolsisMicrosoft’sflagshipdevelopmentproduct,VisualStudio. ThischapterprovidesanintroductiontoVisualStudio2010,thelatestversion.Youwilllearnaboutsome ofthenewfeaturesthatareparticularlyhelpfulfordevelopersbuildingRIAswithSilverlight,andyouwill haveanopportunitytocreateyourfirstSilverlightapplicationusingVisualStudio2010.Let’sgetstarted withabriefintroductiontotheVisualStudioIDE.
WhatIsVisualStudio?
AnydeveloperwhohasdevelopedapplicationsusingtechnologiesrelatedtoMicrosoft’sVisualBasic, ASP,or.NEThasusedsomeversionofVisualStudioonaregularbasis.ThisisbecauseVisualStudiois Microsoft’sprimarydevelopmentproduct.Whetheryouaredevelopingdesktopapplications,web applications,mobileapplications,webservices,orjustaboutanyother.NETsolution,VisualStudiois theenvironmentyouwillbeusing.
VisualStudioisanIDEthatallows.NETdeveloperstoimplementavarietyof.NETsolutionswithin theconfinesofoneeditor.AnIDEisasoftwareapplicationthatcontainscomprehensivefacilitiestoaid developersinbuildingapplications.VisualStudiofitsthisdescriptionforanumberofreasons.First, VisualStudiooffersaveryrichcode-editingsolution.Itincludesfeaturessuchassourcecodecolor-codingandcodecompletion.Second,itoffersanintegrateddebugger,whichallowsyoutoplace breakpointsinyoursourcecodetostopexecutionatanygivenpoint,aswellasstepthroughthesource linebyline,analyzingthestateofobjectsandfieldsatanygivenpointintheexecution.Addtothese featuresrichsupportforapplicationdeployment,installation,andintegrationwithdatabaseservices, andyoucanunderstandhowVisualStudioisanextremelyvaluabletoolfordevelopers.
■
Note
ThisbookassumesabasicunderstandingofVisualStudio.Ifyou’renewtoVisualStudio,Irecommend
The History of Visual Studio
VisualStudiohasquiteahistory.ThefirstversionwascalledVisualStudio97,whichwasmostcommonly
knownforVisualBasic5.0.In1998,MicrosoftreleasedVisualStudio6.0.ThatversionincludedVisual
Basic6.0,aswellasMicrosoft’sfirstweb-baseddevelopmenttool,VisualInterDev1.0,whichwasusedto
developASPapplications.
NextcametheintroductionofMicrosoft.NETandASP.NET1.0,promptingVisualStudio.NET.AsMicrosoft
wasenhancingandreleasingnewversionsofMicrosoft.NETandASP.NET,italsocontinuedenhancing
VisualStudiobyreleasingVisualStudio2003andthenVisualStudio2005.Inaddition,Microsofthas
introducedalineoffreedevelopmenttoolsknownastheVisualStudioExpresstools,aswellastheVisual
StudioTeamSystem,whichcanbeusedbylargeprogrammingteamstobuildenterprise-levelsystems.
MicrosoftreleasedVisualStudio2008underthecodenameOrcasandaddedanumberoffeaturessuch
assomeenhancedJavaScriptdebuggingaswellassomeIDEimprovements.
AsforVisualStudio2010,MicrosoftstartedfromthegroundupanddevelopedtheIDEontopofWPFin
ordertomakeanumberofnewfeaturespossible.
What’sNewinVisualStudio2010?
MicrosofthasintroducedavarietyofnewfeaturesinVisualStudio2010,manyofwhicharegeared towardhelpingdevelopersbuildRIAswithSilverlightandrelatedMicrosofttechnologies,suchasthe WindowsCommunicationFoundation(WCF),ADO.NETDataServices,andAjax.Let’slookatsomeof thenewfeaturesinVisualStudio2010thatareparticularlyhelpfultoSilverlightapplicationdevelopers.
SupportforMultipleMonitors
Todayitiscommonfordeveloperstohavemultiplemonitorsattachedtotheirdevelopment
workstationsand,unfortunately,previousversionsofVisualStudionevertookadvantageofthisextra realestate.Developerscouldusetheextrascreensforotherapplications,butoftenitwouldbenicetobe abletoviewmorethanonesourcefileatonce.VisualStudio2010addssupportformultiplemonitorsby allowingdeveloperstopullsourcefiles,windows,andmoreoutoftheVisualStudioprimaryIDEand movethemtoothermonitors.Take,forexample,Figure2-1.VisualStudio2010isopenontheleft monitor,andweareviewingtheMainPage.xaml.However,IwouldliketoinspecttheclassthatmyUIis boundtoatthesametime.TodosoIcansimplydragtheclassoutofthedockedpositionintheIDEand moveittothesecondmonitor.Icoulddothesamethingforthetoolbox,thepropertieswindow,orany windowwithinVisualStudio2010.Averynicenewfeature!
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
Figure2-1.Multi-monitorsupport
ZoomSupportforSourceEditor
Figure2-2.ZoomingoutintheSourceEditor
ImprovedIntelliSense
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
Figure2-3.ImprovedIntelliSenseinVisualStudio2010
Inadditiontothepartialstringmatching,theperformanceofIntelliSensehasbeendramatically improved.ThisallowsdeveloperstocodewithoutdelaysinIntelliSenseandkeeptheirrollsrolling.
AddReferencesPerformance
InVisualStudio2008andpreviousversions,developershavenoticedthatwhenyouopentheAdd Referencedialog(seeFigure2-4),ittakesquiteabitoftimeforittofulldisplaythelistingof
Figure2-4.AddReferencedialog
ReferenceHighlighting
Whenyouclickanywherewithinasymbol(classname,variable,object,field,etc),allinstancesofthat itemarehighlightedthroughoutthecurrentdocument,asshowninFigure2-5.Thisisnotasimpletext matching;theeditorissmartenoughtounderstandthescopeofthedifferentvariables.Soevenifyou havetwoitemswithidenticalnamesthatbelongtodifferentobjects,theyarenotbothhighlighted.
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
BoxSelection
AnothercoolfeatureofVisualStudio2010isboxselection.Considerthesituationwhereyouwouldhave thefollowingsource:
public string Nickname { get; set; } public string Notes { get; set; } public string Card1 { get; set; } public string Card2 { get; set; }
Let’ssaythatyouwantedtochangeallofthesetobeprivatepropertiesinsteadofpublic.InVisual Studio2010youcanholddowntheAltkeyanddragaboxaroundjustthepublicdeclarations,asshown inFigure2-6.
Figure2-6.BoxselectioninVisualStudio2010
Betteryet,onceyouhavethisboxselectedyoucaneditallofthelinesatonce.Sowiththeselection made,simplytypeprivateanditwillautomaticallyreplacethepublicineachofthelines,asshownin Figure2-7.
Figure2-7.EditingaboxselectioninVisualStudio2010
CallHierarchyWindow
TheCallHierarchywindowdisplaystwolistsregardingagivenmember:Firstallcallstothemember (incoming)andallcallsfromthemember(outgoing).Withineachofthoselists,youcanthendrillinto eachmemberandseeitsincomingandoutgoingcalls,formingaveryusefulcallhierarchy.
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
CodeGeneration
VisualStudio2008introducedtheabilitytogenerateamethodstubfromagivencallinthesource. ConsiderthefollowinglineofcodecallingthemethodSomeMethodthatdidnotexist,andpassingitan integerandastring:
Person.NewMethod(123, "Bob");
Ifyoutypethis,VisualStudiowillprovideyouwiththeoptiontoGeneratemethodstubfor
‘NewMethod’.Byselectingthis,VisualStudiowillautomaticallycreatethefollowingmethodstubinthe
Personclass:
class Person {
internal static void NewMethod(int p, string p_2) {
throw new NotImplementedException(); }
}
VisualStudio2010expandsonthiscodegenerationfunctionalitybynowallowingyouto automaticallygenerateclasses,structs,andenumerations.
ExtensionManager
ManagingextensionsandcontrolshasalwaysbeenastressfulpointwithVisualStudio2008and previousversionsofVisualStudio.InVisualStudio2010theExtensionManagerhasbeenintroduced. Itallowsyoutoeasilybrowseanonlinelibraryfordifferentextensionsaswellasmanagetheextensions thatareinstalledinyourcurrentdevelopmentenvironment.TheExtensionManagerisshownin Figure2-9.
Figure2-9.ExtensionManager
BuildingYourFirstSilverlightApplicationinVisualStudio
ThebestwaytoexploretheVisualStudioIDEistogetyourhandsdirtyandplayaroundwithit.Let’s buildaSilverlightapplication.
TryItOut:HelloWorldinSilverlight4
Inthisexercise,you’llbuildtheHelloWorldSilverlight4application.IpersonallyhatetheHelloWorld sample,butitisusedoftenbecauseitissosimpleandprovidesagoodintroduction.WhoamItobreak withtradition?Let’sgetstarted.
1. StartVisualStudio2010andSelectFile➤New➤Projectfromthemainmenu. 2. IntheNewProjectdialogbox,selectVisualC#astheprojecttype,andinthe
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
Figure2-10.CreatinganewSilverlightproject
Figure2-11.TheNewSilverlightApplicationdialogbox
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010
4. VisualStudiohasalreadyopenedtheMainPage.xamlfile,whichiswhereyou willstartworking.Let’sbeginbyaddingaTextBlockcontrol,whichwilldisplay our“HelloWorld!”message.AddtheTextBlockwithinyourCanvasobject,as follows:
<UserControl x:Class="HelloWorld.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" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="HelloMessage" Text="Hello World!" FontSize="30" /> </Grid>
</UserControl>
5. SavetheprojectandrunitbypressingF5.IfyouseetheDebuggingNot Enableddialogbox,select“ModifytheWeb.configtoenabledebugging”and clickOK.TheresultshouldbeasshowninFigure2-13.
Figure2-13.YourfirstSilverlightapplicationinVisualStudio2010
6. Iknowthisisn’tveryinteresting,solet’schangethingsupabitbysettingthe displaymessageintheMainPage.xaml.cscodebehind.Inthecodebehind,you willnoticeaconstructorforyourPageclass,whichcontainsonemethodcalled
InitializeComponent().Underthatmethod,changetheTextpropertyofyour
namespace HelloWorld {
public partial class MainPage : UserControl {
public MainPage() {
InitializeComponent();
this.HelloMessage.Text = "Hello Universe!"; }
} }
7. Rebuildtheapplicationandrunitagain.YourresultshouldlooklikeFigure 2-14.
Figure2-14.ThefinalresultfromourfirstSilverlightapplicationinVisualStudio2010
8. Closetheapplication.
Thereyougo!YouhavebuiltyourfirstSilverlightapplication.Ofcourse,thisapplicationis extremelysimple,butyoudidgetanideaofhowthingsworkinVisualStudio2010.
HostingYourSilverlightApplication:WebSiteorWebApplication?
CHAPTER2■ INTRODUCTIONTOVISUALSTUDIO2010 youwon’thaveabindirectory.
ThefollowingaresomeadvantagesofusingaVisualStudiowebsite: website,youmustrenamethefile,addingtheextension.exclude.
UsingaVisualStudioWebApplicationProject
Summary
ThischapterintroducedVisualStudio2010andsomeofthenewfeaturesofferedinthisversion, includingthenewJavaScriptIntelliSensefeatures,supportformultiplemonitors,andmanaging extensions.Inaddition,youbuiltyourveryfirstSilverlightapplication.
C H A P T E R 3
■ ■ ■
Layout Management in Silverlight
ThepreviouschapterprovidedanoverviewofVisualStudio2010,oneoftheprimarytoolsusedin developingSilverlightapplications.Inthischapter,youaregoingtostarttodiveintosomeSilverlight developmentbylookingatthelayoutmanagementcontrols.
Asyouhavelearned,SilverlightapplicationsconsistofanumberofSilverlightobjectsthatare definedbyXAML.Layoutmanagementinvolvesdescribingthewaythattheseobjectsarearrangedin yourapplication.Silverlightincludesfivelayoutmanagementcontrols:Canvas,StackPanel,Grid,
WrapPanel,andDockPanel.Youwilltakealookateachofthesein-depth.Bytheendofthischapter,you shouldhaveagoodunderstandingofwhentousewhichlayoutcontrol.
Let’sbeginbylookingatthemostbasiclayoutcontrol:theCanvaspanel.
Table3-1.LayoutControlProsandCons
Control Description
Pros
Cons
Canvas Basedonabsolute positionof controls.
Verysimplelayout. Requiresthateverycontrolhavea
Canvas.TopandCanvas.Left propertyattachedtodefineits positiononthecanvas.
StackPanel Basedon horizontalor vertical“stacks”of controls.
Allowsforaquickdynamic layout.NestingStackPanel controlscanprovidesome (withtheVerticalAlignmentand
Continued
Control Description
Pros
Cons
Grid Mimicsusingtable elementsinHTML theGridcontrol.
Griddefinitionscangetsomewhat complexattimes.NestingGrid componentscanbeconfusing.
WrapPanel Basedonhorizontal orvertical“stacks”of
DockPanel Layoutisbasedon “docked”horizontal
CHAPTER3■ LAYOUTMANAGEMENTINSILVERLIGHT
TheobjectswithinaCanvaspanelhavenolayoutpoliciesplacedonthembythelayoutcontroland willnotresizeautomaticallywhenyourapplicationisresizedwithinthebrowser.
TryItOut:UsingtheCanvasPanel
Let’stryoutaquickexampleofusingtheCanvaspanel.
1. OpenVisualStudio2010andcreateanewSilverlightapplicationcalled
CanvasPanel.AllowVisualStudiotocreateaWebApplicationprojecttohost theapplication.
2. Whentheprojectiscreated,youshouldbelookingattheMainPage.xamlfile.If youdonotseetheXAMLsource,switchtothatviewsoyoucanedittheXAML. WithinthemainGridelement,addaCanvaselement.AssignitaWidthproperty of300andaHeightpropertyof300.InordertoseetheCanvaspanelinthe application,alsosetthebackgroundcolortogreen.ThefollowingXAMLadds thisCanvas:
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Background="Green" Width="300" Height="200"> </Canvas>
</Grid>
Figure3-2.DefaultCanvaswithagreenbackground
3. Let’saddabuttontothisCanvaspanel.Addthefollowingcodetoplacethe button,whichhasthelabelButton1,aWidthpropertyof100,andaHeight propertyof30.(TheButtoncontroliscoveredindetailinChapter4.)
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Background="Green" Width="300" Height="200"> <Button Width="100" Height="30" Content="Button 1" /> </Canvas>
</Grid>
CHAPTER3■ LAYOUTMANAGEMENTINSILVERLIGHT
Figure3-3.Singlebuttonwithinthecanvas
4. Let’saddanotherbuttontotheCanvas,butthistimepositionitbelowandabit totherightofthefirstbuttonbysettingitsCanvas.TopandCanvas.Leftas attachedproperties.GivethisbuttonthelabelButton 2,asfollows:
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Background="Green" Width="300" Height="200"> <Button Width="100" Height="30" Content="Button 1" /> <Button Width="100" Height="30" Content="Button 2" Canvas.Left="10" Canvas.Top="40" /> </Canvas>
</Grid>
Figure3-4.Twobuttonspositionedrelativetothecanvas
CHAPTER3■ LAYOUTMANAGEMENTINSILVERLIGHT
FillingtheEntireBrowserWindowwithYourApplication
Bydefault,inanewSilverlightproject,therootUserControlobjectissettoawidthof400andaheightof 300.Insomecases,youmaywishtosetthewidthandheightofyourSilverlightapplicationwithinthe browser.Atothertimes,however,youwillwantyourSilverlightapplicationtotakeuptheentirewindow ofyourbrowser,andtoresizeasthebrowserisresized.ThisisdoneveryeasilywithinSilverlight.When youwishforthewidthandheighttobesetto100%,simplyomittheelement’sHeightandWidth attributes.
Asanexample,thefollowingsourcehasbeenadjustedfortheCanvaspanelandtheSilverlight applicationtotakeuptheentirebrowser:
<UserControl x:Class="FillBrowser.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" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" Background="White"> <Canvas Background="Green">
</Canvas> </Grid>
</UserControl>
WiththeomissionoftheHeightandWidthdeclarationsforUserControlandCanvas,whenyourun theSilverlightapplication,youwillseethatthecanvastakesup100%ofthebrowserwindow,asshown inFigure3-6.Itwillresizeasthebrowserresizes.
Asyou’veseen,theCanvaspanelisasimplelayoutcontrol.Itcanbeusedveryeffectivelyinafixed layout.However,inmostcases,youwillwanttouseastaticlayoutforyourapplications.TheStackPanel controlprovidesamorefluidlayoutcontrol.
TheStackPanelControl
TheStackPanelprovidesdeveloperswithaquicklayoutoptionforpositioningobjects.TheStackPanel controlallowsyoutopositionSilverlightobjectsinmoreofaflowlayout,stackingobjectseither horizontallyorvertically.Figure3-7showsthebasicconceptofthislayoutcontrol.
Figure3-7.TheStackPanelcontrolorientations
TryItOut:UsingtheStackPanelControl
TobetterunderstandtheStackPanelcontrol,let’srunthroughanexercise.
1. InVisualStudio2010,createanewSilverlightapplicationnamed
Ch3_StackPanelandallowVisualStudiotocreateaWebSiteprojecttohostthe application.
CHAPTER3■ LAYOUTMANAGEMENTINSILVERLIGHT
<Grid x:Name="LayoutRoot" Background="White"> <StackPanel>
<Button Width="100" Height="30" Content="Button 1"></Button> <Button Width="100" Height="30" Content="Button 2"></Button> <Button Width="100" Height="30" Content="Button 3"></Button> </StackPanel>
</Grid>
Atthispoint,yourapplicationshouldappearasshowninFigure3-8.Notice thatthebuttonsarestackedvertically.Thisisbecausethedefaultstacking orientationfortheStackPanelcontrolisvertical.
Figure3-8.TheStackPanelcontrolwithitsdefaultorientation
ChangetheorientationoftheStackPanelcontroltobehorizontalbysetting theOrientationpropertytoHorizontal,asfollows:
<Grid x:Name="LayoutRoot" Background="White"> <StackPanel Orientation="Horizontal">
<Button Width="100" Height="30" Content="Button 1"></Button> <Button Width="100" Height="30" Content="Button 2"></Button> <Button Width="100" Height="30" Content="Button 3"></Button> </StackPanel>
Withthissimplechange,thebuttonsarenowstackedhorizontally,asshownin Figure3-9.
Figure3-9.TheStackPanelcontrolwithhorizontalorientation
2. Noticethatallthebuttonsaretouchingeachother,whichisunattractive.You caneasilyspacethemoutbyusingtheirMarginproperty.Inaddition,youcan centerthebuttonsbysettingtheStackPanelcontrol’sHorizontalAlignment propertytoCenter.OtheroptionsforHorizontalAlignmentincludeLeft,Right, andStretch(whichstretchesthecontenttotheleftandright).Makethe followingchangestoadjustthebuttons:
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button Width="100" Height="30" Content="Button 1"
Margin="5"></Button>
<Button Width="100" Height="30" Content="Button 2" Margin="5"></Button>
<Button Width="100" Height="30" Content="Button 3" Margin="5"></Button>
</StackPanel> </Grid>
CHAPTER3■ LAYOUTMANAGEMENTINSILVERLIGHT
Figure3-10.TheStackPanelcontrolwithbuttonsspacedapartandcentered
TryItOut:NestingStackPanelControls
Microsoftdesignedthecontrolframeworksothatanyobjectcanbecontainedwithinanotherobject. Onewayyoucanenhanceyourlayoutisbynestingalayoutcontrolwithinanotherlayoutcontrol.In thisexample,youwillnestaStackPanelcontrolwithinanotherStackPanelcontrol,butrealizethatyou cannestanylayoutcontrolwithinanyotherlayoutcontroltogettheexactlayoutfunctionalityyouare seeking.
1. InVisualStudio2010,createanewSilverlightapplicationnamedNestedStackPaneland allowVisualStudiotocreateaWebApplicationprojecttohosttheapplication.
2. IntheMainPage.xamlfile,addthefollowingitems:
• AStackPanelcontroltotherootGridwithitsOrientationpropertysetto
HorizontalandtheHorizontalAlignmentpropertysettoCenter.
• WithinthatStackPanel,addtwobuttonswiththelabelsButton Leftand
Button Right.
• Inbetweenthetwobuttons,addanotherStackPanelwithOrientationsetto
VerticalandVerticalAlignmentsettoCenter.