Applied WPF 4 in Context Free ebook download
- LearnXAML(theExtensibleApplicationMarkupLanguage)through
- SeehowtointegrateWindowsForms,DirectX,ActiveX,orothernon-WPF
- DiscoverhowtointegrateWPFwithreportwriterssuchasCrystalReports andSQLServerReportingServices.
- Understandhowtoaccessremoteservicesonaserverfromtheclientmachine usingWindowsCommunicationFoundation.
Contents at a Glance
AbouttheAuthor................................................................................... Acknowledgments....................................................................................
Chapter1:IntroducingWPFandXAML................................................................ ■
Chapter2:SampleApplication:OverviewandGettingStarted ■
Chapter3:MicrosoftExpressionBlend.............................................................. ■
Chapter4:CreatingtheViews...................................................................... ■
Chapter5:AddingControlstotheViews............................................................ ■
Chapter6:TheEntityFramework.................................................................... ■
Chapter7:DataBinding............................................................................ ■
Chapter8:CommandHandlingandEventRouting ■
Chapter9:TestingwithTDD........................................................................ ■
Chapter10:ReportswithMicrosoftReportingServices ■
Chapter11:DeploytheApplicationUsingClickOnce ■
Chapter12:DesignPatternsinWPF................................................................. ■
Chapter13:WPFandMultithreading................................................................. ■
Chapter14:InteractingwithWCF................................................................... ■ Index..............................................................................................
Introduction
WindowsPresentationFoundation(WPF)isagraphicalcomputerplatformbuiltanddistributedby MicrosofttocreaterichclientapplicationsforWindowssystems.WithWPF,youcanbuildrich interfaceswithanimationsandamazinggraphicaleffectsaseasilyasyoucanbuildminimalistand corporateuserinterfacesforline-of-business(LOB)applications.Unfortunately,becauseWPFissucha powerfulandcomplextechnology,itrequiressomeinitialefforttounderstanditsmechanisms. Moreover,foranewbie,theXAMLmarkupusedtocreatetheuserinterfacescanbetoughtocometo gripswith.
CreatingaWPFapplicationand,moregenerally,creatinganytypeofapplicationwithauser interfaceisaratherconvolutedtask;itcomprisesanumberofphasesandthefinalresultislikelytobeof acertaincomplexity.AstandaloneapplicationbuiltusingWPFisusuallymadeupofvarious “components”thatareusedtoencapsulatethe“modules”ofthesoftware.Youmighthave,forinstance, acomponenttoaccessthedata,acomponenttoincludealogicalfunction,acomponenttorenderthe userinterface,andsoon.
Inthisbook,IwillshowyouhowtocreateandimplementWPF,usingbestpracticestocreateareal- worldapplication.Atthesametime,I’llalsoshowyouhowtostructureandarchitectaWPFapplication madeupofdifferentcomponentsthatyou’llbeabletorecycleforfutureapplications.Bytheendofthe book,youshouldhaveaworkingknowledgeofWPFandknowhowtoarchitectaWPFapplicationusing thetoolsprovidedbyMicrosoft,suchasSQLServer2008R2ExpressEdition,theEntityFramework, WindowCommunicationFoundation(WCF),andmore.
WhoThisBookisFor
ThisbookisforWindowsapplicationdeveloperswhowanttounderstandthecontextinwhichWPFsits andthestandardsandbestpracticesthatcanbeemployedtoimprovetheefficiencyandmaintainability oftheirprojects.
HowThisBookisStructured
Thebookisdividedintochaptersbuttheoverallstructurefollowsaspecificlogic,soIsuggestyouread thechapterssequentially—especiallyifthetopicisnewtoyou.ThebookexplainshowtobuildaWPF applicationfrombeginningtoend.Youwillstartbyanalyzingtheuser’srequirementsbeforesettingout tocreatetheapplication,andthenyou’lllearnhowtoworkwithMicrosoftExpressionBlendtolayout theuserinterfacethatistheessenceoftheapplication.Onthewayyou’lllearnaboutAgiledevelopment conceptssuchasDomainDrivenDesign,Object-RelationalMappers,thebusinesslayer,andService- OrientedArchitecture.Thereisevenonechapterdedicatedtomultithreadingandparallelprogramming inWPF,andmoregenerallywiththe.NETFramework,andIhavealsodedicatedachaptertothe reportingtoolofferedforfreewithMicrosoftSQLServer2008R2Expressedition,SQLServerReporting Services.
Attheendofthebook,you’llbeabletodeploytheapplicationusingClickOnceandIIS,andyou’ll understandhowWPF’sdistributionmechanismworks. DownloadingtheCode
Thesourcecodeforthisbookisavailabletoreadersatownloadsectionofthe book’spage.PleasevisittheApresswebsitetodownloadallthecode.Youcanalsocheckforerrata,and findrelatedApresstitles.
ContactingtheAuthor
Youarewelcometocontacttheauthor,RaffaeleGarofalo(akaRaffaeu),withquestions.Youcanreach himat Followhimontwitter@Raffaeu.
C H A P T E R 1
■ ■ ■
Introducing WPF and XAML
DevelopedbyMicrosoft,WindowsPresentationFoundation(WPF)isagraphicalsubsystemfor renderinguserinterfacesinaWindowsoperatingsystem.WPFisbasedonamarkuplanguagealso knownasXAML.
XAML,whichisanacronymforExtensibleApplicationMarkupLanguage,isadeclarativemarkup languageavailableinthe.NETFrameworkdesignedtosimplifytheUIcreation.XAMLisappliedto differenttechnologies;itisavailableforWindowsPresentationFoundation,Silverlight,andWindows WorkflowFoundation(WF).
TheprincipalreasonofhavingamarkuplanguagefortheUIcreationistodecoupletheUIcode fromthepresentationlogicthatcanstillbewritteninoneoftheavailable.NETlanguagessuchasC#or
VB.NET.Usingthisapproach,youcanassigntheUIdevelopmentprocesstoadeveloper/designermore specializedintheUIcreation,whowillprobablyuseExpressionBlend,andyoucanleavethecore developmentprocesstoa.NETdeveloper,whowillprobablyaccomplishthistaskusingVisualStudio.
Usually,butnotalways,aXAMLfilewillhaveanextensionoftype.xamlandanencodingoftype UTF-8;Listing1-1showstheXAMLcodetocreateaWPFcontrol.Thisspecificcodeisdeclaringa
StackPanelcontrolthathasaListBoxcontrol;insidetheListBoxthreeitemsaredefined,eachoneusing
aListBoxItemelement.
Listing1-1.SampleXAMLCodeUsedtoCreateaButtonControl <StackPanel> <ListBox> <ListBoxItem Content="One" /> <ListBoxItem Content="Two" IsSelected="True" /> <ListBoxItem Content="Three" /> </ListBox> </StackPanel>
BeforestartingtolearnhowWPFworks,youshouldanalyzeinmoredetailtheXAMLsyntax,which ispartoftheWPFtechnology.
NoteEspeciallyifyouhavealreadyworkedinthepastwithXAML,youmayfindthisintroductionrepetitive.This ■ isnotbecauseIhadtheintentionofwritingaverboseintroductionbutbecausetheXAMLtechnologyandsyntax areuniqueacrossdifferenttechnologies;soifyoueverworkedinthepastwithaXAMLtechnologylikeSilverlight orWorkflowFoundation,youmayalreadyunderstandthematerialinthenextsections. The XAML Syntax
TheXAMLlanguageisacomplexandveryflexiblemarkuplanguageappliedtodifferenttechnologiesby usingdifferentreferencesintheXAMLfilesothatyoucanrefertodifferentobjectsthatprovidedifferent
XAMLelementsandattributes. LikeanyotherXMLfile,aXAMLfilemusthaveavalidstructureandmustfollowsomespecificrules; oneoftheserulesisthepresenceofavalidrootelement.
NamespacesandRootElements
InXAMLyoudefinearootelementastherootofyourXAMLdocument;thisisamandatoryrequirement fortheXAMLfileandfortheXMLvalidation.InaWPFcontext,therootelementofaXAMLfilewillbea
Page,UserControl,orWindowifyouarecreatingaUIcontainerorasimpleResourceDictionaryifyouare
creatingacollectionofresourcesforyourapplication(whichisanothervalidrootelementforaWPF applicationandwhichisalsoastandardfilecreatedbytheVisualStudioproject).Theserootelements areonlysomeoftheavailableoptionsforaWPFXAMLfile.
■ NoteIfyouarecreatingaXAMLfileforanothertechnologylikeSilverlightorWorkflow,youwillprobablyuse
differentrootelementsprovidedbythesetechnologies.Listing1-2showsthestructureofaWindowobject,whichconstitutesanormalwindowUIinWPF andisrepresentedbytherootelementWindow.
Listing1-2.XAMLRootNamespaces <Window x:Class="Chapter01.MainWindow"
Title="MainWindow" Height="350" Width="525"> <Grid> </Grid> </Window>
TherootelementintheListing1-2containstheattributesxmlnsandxmlns:x.Theseattributes indicatetoaXAMLprocessorwhichXAMLnamespacescontainthetype.Thexmlnsattributespecifically indicatesthedefaultXAMLnamespace.Thexmlns:xattributeindicatesanadditionalXAMLnamespace, whichmapstheXAMLlanguagenamespace(whichis).
ThenamespacedeclarationalwaysappliestoallthedescendantelementofaXAMLdocument,just astheydoforanXMLdocument;forthisreason,youwon’tneedtodeclarethesamenamespacetwice inaXAMLdocumentinordertouseitstypes,butyouwillneedtodeclarethosetypesprecededbythe correspondingelementprefix.
Youmayalsoneedtoreferenceacustomtypeprovidedbyanamespacethatyouhavepreviously createdandthatisalreadyreferencedinyourXAMLapplication;todothat,youshouldusethekeyword
xmlnsfollowedbyyourcustomprefixandthenaddareferencetothenamespacecontainingtheclasses
youwanttouse.
Listing1-3.XAMLfilewithcustomreferences <Window x:Class="Chapter01.MainWindow"
xmlns:custom="clr-namespace:Chapter01.CustomNamespace"
Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <custom:CustomClass /> </Window.DataContext> <Grid> </Grid> </Window>
Listing1-3declaredanewcustomprefixcalledcustom,whichreferencesanamespacethatis referencedintheexampleproject.InsidethisnamespaceisaclasscalledCustomPrefixthatisavailable usingtheprefixcustom.
ObjectsandCommonElements
LikewhenusingXML,ifyouwanttodeclareanewtypeinXAML,youshouldencapsulatethetypeinan elementobjectthatisdenotedbyanopeningbracket(<)followedbythetypenameandthenaclosing bracket(>).Theelementcanbeclosedbyanadditionalelementofthesametype,startingwiththe bracket(</)orcanbesimplyself-closedusingthesyntax/>attheendoftheelementdeclaration.
<!-- closed with another element --> <Button name="MyButton"> </Button> <!-- self-closed --> <Button name="MyButton" />
AssoonasyoudeclareatypeinXAML,itislikeyouarecreatinganewinstanceofthatelement;at thatpoint,youcanaccessthepropertiesandothercharacteristicofthatobjectusingtheXAMLsyntax. The Attribute Syntax
Ifyoucreateanobjectwitha.NETlanguagelikeC#orVB.NET,youcanaccessandmodifyapropertyor avisiblefieldofthatobjectusingthedotsyntax,likethisone:myObject.Property = "myValue".Inthe sameway,afteryoudeclareandinstantiateatypeinXAML,youcanaccessandmodifytheproperties availableforthattypebutinadifferentfashion—usingtheXAMLattributes.Forexample,thefollowing codeisdeclaringaButtonasaXAMLtype,andthenyouaremodifyingitspropertiesusingtheXAML attributes:
<Button Height="40" Width="120" Content=”Hello World!” />
YouareabletoaccomplishthesametaskusingC#:
Button button = new Button(); button.Content = "Save Entity"; button.Width = 100; button.Height = 100;
ThefirstdifferenceyoumaynoticeisthatinXAMLyoudon’tprovideavalueforapropertybased onitsdatatype,whileyouhavethisdistinctioninC#andVB.NET.Forexample,thepropertyWidthofa
ButtonhasanInt32datatype,butinXAMLyoumustspecifyitsvaluebetweentwoquotationmarks,so
anyvalueisspecifiedasaStringvaluetype.ThisisnotreallyaXAMLrequirement,butitisinherited fromtheXMLstructure,whichrequiresavalueforanattributebetweentwoquotationmarks.The conversionisthenappliedusingaTypeConverterAttrbute,whichisexplainedinthenextsection.
The TypeConverterAttribute
AnyvalueusedinanattributeinXAMLisoftypeStringwhenitisinsertedintheXAMLmarkup;this valueneedsthentobetranslatedbytheXAMLprocessortotherealvalueusedbythatelement.For example,youcansettheWidthofaPanel,whichisanintegervalue,to200;theXAMLprocessorwillneed thentoconvertthisstringintoanintegervalue.
IfthevalueisaprimitivethatisunderstoodbytheXAMLparser,adirectconversionofthestringis attempted;ifthevalueisneitheraparser-understoodprimitivenoranenumeration,thenthetypehasto provideatypeconverterclass.
Let’suseforthisexampletheBackgroundpropertyofacommonWPFcontrollikeaButtoncontrol. WhenyoudeclarethevaluefortheBackground,youhavetopassanacceptablevalueoftypeBrush, becauseBrushisthevaluetypefortheBackgroundpropertyandyouwriteaXAMLmarkuplikethis:
<Button Background="Red" />.TheTypeConvertforaBrushvaluetypeiscomposedbyaBrushConverter
thatisassociatedtotheBrushclassusingsyntaxlikethefollowing:
[TypeConverter(typeof(BrushConverter))] public class Brush { // code used for the conversion }
TheXAMLmarkupusedtodefineabackgroundcolorcanthenbetranslatedinthefollowingC# code:
Button b = new Button(); b.Background = new BrushConverter().ConvertFromString("Red");
Ifyouplantocreateacustomtypeconverterforyourcustomtypes,thesearethestepsyouneedto follow: Createacustomclassthatrepresentsyournewconverter;theclassmustinheritfromTypeConvert andmustimplementthemethodsCanConvertFrom,CanConvertTo,ConvertFrom,andConvertTo. Decoratetheclassthatrepresentsyourcustomvaluewithyourcustomconverterusingthe decorationattribute[TypeConvert(TypeOfConvert)].
Property Element Syntax
Sometimes,youmayfinditdifficulttorepresentacomplextypeasaStringvalueforanelement propertyvalue,sothevalueshouldbedeclaredusingadifferenttechnique.Forexample,aButtonhasa
ContentpropertythatrepresentsthecontentoftheButton.InXAML,thecontentcanbesimple,likea String,orcomplex,likeaPanelwithnestedUIcontrols.Ifyouwanttoaddsuchakindofcontentina Button,youmayneedtousethepropertysyntaxelementdefinition,wherethepropertyofanelementis
specifiedasanadditionalelement,achildone. ThefollowingcodeshowsaButtonwithacomplextypeforitsContentproperty.Inthisexample, youarerepresentingthecontentofaButtonusingaStackPanelthatincludestwocontrols:anImagethat willdisplaythebutton’siconandaTextBlockthatwilldisplaythebutton’scaption.
<Button Height="40" Width="120"> <Button.Content> <StackPanel Orientation="Horizontal"> <Image Source="home_go_32.png" Margin="0,0,5,0" /> <TextBlock VerticalAlignment="Center" Text="HomePage"/> </StackPanel> </Button.Content> </Button>
Thepropertyelementsyntaxisrepresentedbythenameoftheparentelement,followedbyadot thatisfollowedbythenameoftheproperty.Inthisway,thepropertyelementbecomesacomplete
XAMLelementthatcanincludeachildstructure. Youcanusethesametechniquetodeclareacollectionofvalues.Ifthepropertyelementyouare workingwithisoftypecollection,youcandeclareasetofsequentialchildelementsinsideit,likeinthe followingcode,whichisdeclaringasetofchilditemsforaListBoxelement:
<ListBox> <ListBox.Items> <ListBoxItem Content="One" /> <ListBoxItem Content="Two" IsSelected="True" /> <ListBoxItem Content="Three" /> </ListBox.Items> </ListBox>
AsyoucanseetheItemspropertyhasacollectionofitemsoftypeListBoxItemdeclaredsequentially inthepropertyelement.
The Content Property
InXAMLthereisaparticularpropertyavailableforanyelement,whichisthedefaultpropertythatis definedbyContentPropertyAttribute;iftheelementrepresentsaclassderivedfromControls.
ContentControl,thedefaultpropertyisoftypeContentProperty;forotherelementsliketheTextBlock,
thedefaultpropertyistheInlinesproperty,andsoon.AnyclassrepresentedbyXAMLcanhaveone andonlyonecontentpropertythatcanbeconsideredasthedefaultpropertyforthatclass.Becausethis propertyisthedefaultpropertyofaclass,youcantotallyomititsdeclarationinXAML;inordertouseit inthisway,youshouldsimplyaddcontentinsidetheclasselement.Ofcourse,noteverycontent propertyisthesame;forexample,youmayhaveacontentpropertyoftypeStringandacontent propertyoftypeObject.
Listing1-4showshowyoucanimplicitlyorexplicitlydeclarethecontentvalueofaTextBlockin
XAML.
Listing1-4.XAMLImplicitandExplicitContentDeclaration <StackPanel> <!-- IMPLICIT --> <Button>I am implicit content</Button> <!-- EXPLICIT --> <Button> <Button.Content> I am explicit content </Button.Content> </Button> </StackPanel>
Inthesameway,youmayneedtodeclarethecontentofaspecificelementusingthecollection syntaxbecausethecontentpropertyisoftypecollection.Thisisthecasethatappliestoanycontainer controlinWPF,likeaPanel,aStackPanel,andsoon,wherethedefaultpropertyisoftypeChildren. Thesetypesofcontrolshaveatypeconverterfortheircontentpropertythatistranslatedinacollection ofchildcontrols.
Listing1-4hasarootelementoftypeStackPanel,anditscontentpropertyisimplicitlypopulatedby twochildelements,namely,twobuttons.
TheCodeBehind
EverytimeyoucreateanewXAMLfileinVisualStudio,itwillcreateforyouacode-behindfilebasedon thelanguageofyourproject;soifyouareworkingonaWPFapplicationusingC#,afteryoucreateafile calledMainWindow.xaml,thenVisualStudiowilladdforyouafilewiththesamenamebutwiththe.cs extension,MainWindow.xaml.cs,whichcontainsthecorrespondingC#ofyourXAMLfile.
IfyoulookmoreindepthinaXAMLfilecreatedinVisualStudio,youwillnoticethatinthe ofyourXAMLfile.WhenVisualStudiocompilesyourfile,theCLRwillputtogethertheXAMLfileandthe code-behindbasedonthenameinthex:Classattribute;inthesameway,ifyourXAMLfiledoesn’thave acode-behindfile,thex:Classattributewillnotbeused. WhenyouworkonaWPFapplication,youwillalwayshaveacode-behindfileforeachXAMLfile createdinyoursolution;inthisfileyouwillsavetheC#coderelatedtotheXAMLfileandalltheevents anddelegateassociatedwiththatUserControl.
Events in XAML
IfyouhaveeverworkedwithWPForwithanotherclienttechnologysuchasWindowsForms,you alreadyknowthatforeachcontrolthereisaspecificeventraisedinordertoinformtheUIthattheuser didsomething.Forexample,whenyouclickaButton,theUIraisesaneventClickassociatedtothat button.
InWPFandinXAMLingeneral,youcan’twritetheproceduralcodeforthateventintheXAMLfile, butyouneedtowritethecorrespondingeventhandlerinaC#file. Listing1-5showsaXAMLButtonwithamethodassociatedtoitsClickevent.Themethodis registeredintheXAMLcode,butit’sdeclaredexplicitlyinthecode-behindfile.
Listing1-5.C#EventonaCode-BehindFile // XAML File <Button Click=”Click_Event”>Hello World</Button> // C# Code-behind private void Click_Event(object sender, RoutedEventArgs e) { Console.WriteLine(“Hello World”); }
CautionInXAMLyoucanalsoincludetheproceduralcodeintheXAMLfilebyusingthissyntax: ■ <x:Code><![CDATA[ // your code here … ]]></x:Code> IsuggestyouavoidthistechniquebecauseoneoftheaimsofXAMListoseparatetheUImarkupfromthe presentationlogic.
EventsarefundamentalinWPF,andyouwillseeinthisbookhoweventsarehandledinWPFusing commandsandroutedevents.
AttachedProperties
XAMLisapowerfullanguagethatcanbeeasilyextendedusingtheelementprefixortheattached properties.YoualreadysawthatafteryoudeclareanadditionalnamespaceinaXAMLrootelement usingaprefixalias,yougetasetofnewelementsavailableinthatnamespace.
Withtheattachedproperties,youattachelementadditionalpropertiesprovidedbytheparent elementintheformofrealproperties. Usually,someelementsprovideanattachedpropertytotheirchildelementsbecausetheywantto knowsomethingfromtheminordertoreactintheproperway.Forexample,WPFprovidesacontainer controlcalledDockPanelthatallowsyoutopilethechildcontrolsofthispanelusingthedockposition. Theavailabledockpositionsareleft,right,top,andbottom.ForeachchildelementofaDockPanel,you canandshouldspecifyadifferentdocklocation;youmayhavealabelatthetop,atextboxinthe middle,andabuttonatthebottom.Toaccomplishthistask,theDockPanelattachesapropertycalled
Docktoeachchildelement.
Becausethepropertyisnotprovidedbythechildelement,youneedtousethesyntax
Parent.Property;Listing1-6showsapracticalexampleofanattachedproperty. Listing1-6.AttachedPropertyinXAML <DockPanel Width="200"> <TextBlock DockPanel.Dock="Top">First Name:</TextBlock> <TextBox DockPanel.Dock="Top" /> <Button DockPanel.Dock="Bottom">Save</Button> </DockPanel>
TheattachedpropertiesarenottheonlyavailableextensioninXAMLprovidedbytheparent element;forexample,someelementscanprovidetothechildrenanattachedeventthathasthesame logicofanattachedproperty,butit’sanevent.
NoteInthisshortintroduction,yousawhowXAMLworksandhowXAMLisstructured.Inthenextchapters,you ■
willlearnhowXAMLisstructuredandhowitcanbeusedforaWPFapplication.Ifyourintentionistoanalyze
morein-depthspecifictopicsrelatedtotheXAMLtechnologyortotheXAMLsyntax,Isuggestyouvisitthe
followingURL:Introduction to WPF
WPFistheMicrosoftXAMLtechnologyforclientapplicationshostedonaWindowsoperatingsystem. ThecurrentversionofWPFisthe4.0,whichisdeliveredwiththe.NETFramework4. WPFisavectorialUItechnologythatusesXAMLasamarkuplanguagetodefinetheUIandusesC# orVB.NETforthepresentationlogic. AWPFapplicationcanbebuiltwithasimpletexteditorandtheC#compilercarriedwiththeNET
Framework(it’satoughjob,butitcanbedone);withoneoftheavailableversionsofVisualStudio2010 orwithExpressionBlendwhichrequiresboththeNETFrameworkruntime.VisualStudioisforamore development-orientedaudience,andExpressionBlendisforamoredesigner-orientedaudience.
Asyoualreadysawintheprevioussection,aWPFapplicationand,ingeneral,aXAMLfilemaybe composedbyaXAMLmarkupfilethatdefinestheUIstructureofacontrolandacode-behindfileinC# orVB.NETthatdefinesthebehaviorsofthecontrol.
Rightnowthe.NETFrameworkallowsyoutobuildtwodifferenttypesofWPFapplications;thefirst oneisidentifiedasastand-aloneapplication,anditiscomposedoftheclassic.exefilethatcontainsall theexecutablecodeandrunsonaWindowsoperatingsystem.Thesecondoneisanin-browser applicationandhasan.xbapextensionthatcanbeexecutedinInternetExplorer.
Figure1-1showsaschematizedversionofhowWPFcanactasastand-aloneapplicationoranin- browserapplication.Themaindifferenceisintheprojecttypeandinthecontainersyouwilluseto displaytheUI.Althoughastand-aloneapplicationdisplayswindows,anin-browserapplicationdisplays pages.
Figure1-1.ExampleofStandAloneandBrowserapplication UI Controls in WPF
AlthoughWPFisaveryflexibletechnology,youmaystillhavetheneedadefaultsetofcontrolsand containerswhileyouarewritingyourapplications,andWPFcomeswithadefaultsetofcontrolsand containersthatcansatisfymostofyourneeds.
Inadditiontothesecontrols,youmayfinditusefultovisittheopensourcecommunityatCodePlex
),whereyoucanfindhundredsoffreecontrolsandcontainersforyourWPF
applications.Inthisbook,youwillusesomeofthesecontrolstobuildanOffice-styleapplication. YoucanaddWPFcontrolstotheviewusingtheXAMLmarkuplanguageoratruntimeusingthe code-behindfile;youmayneedtocreateaparticularUserControlthatwillneedtocreatechildcontrols
ontheflywhiletheapplicationisrunning,andyoumayneedtoaccomplishthistaskusingthe
proceduralcode(C#orVB.NET).
ControlsContainers
ThefirstthingyoumayneedtounderstandwhenyouwriteaWPFapplicationoranyUIapplicationis howtopositionyoucontrolsintheview(seethefollowingnote).WPFisavectorialtechnology,which meansitisabletoadaptthescreenresolutionwithoutlosingqualityintheUI.
InWPFthetermframeworkelementmeansatheoreticalrectanglethatrepresentsaportionofthe UI.EachcomponentoftheUIisarectangle,andeachchildcomponentisanadditionalrectangle.The allocationallowedforarectangleintheUIisaffectedbythepresenceofadditionalcontrolsinthesame container;forexample,youmayhaveaStackPanelthatcontainsonlyaTextBox.Inthiscase,theTextBox willcovertheentirespaceprovidedbytheStackPanel;ifintheStackPanelyoupositionanadditional
TextBox,thespacewillbecoverednowbythetwochildcontrols.
Figure1-2showsapracticalexample.
Hello World Nr.1 Hello World Nr.2 Hello World Nr.3
Figure1-2.WPFStackPanelwiththreeTextBoxcontrols
Asyoucansee,inthiscase,eachTextBoxisoccupyingtheentirewidthoftheparentcontrol containerbecauseitisusingaverticalflow;withanothercontainer,thebehaviormayresultin somethingdifferent.
■ NoteWiththetermview,wedefineanyUIcontainersuitabletoofferagraphicalrepresentationofthedataand aninteractionbetweentheapplicationandtheuser.InWPFaviewcanbeawindow,amodaldialog,orasimpler usercontrol.
WithWPFyouhavedifferentwaysofpilingthecontrolsinacontaineranddifferentwaysofresizing thecontrolsinthecontainerwhenthecontainersizechangesorwhenthescreenresolutionsize changes.TheinterestingnewsisthatwithWPFyoudon’tneedanythingelsetoprovidethecodeforthe resizingprocessbecausethecontrolscontainerisinchargeofthat.
Layoutcontainershavedifferentbehaviors:
- Canvas:Definesanareawhereeachchildcontrolispositionedbyprovidingan absolutecoordinatesvalue.ThisisthesamebehavioryouhadinWindowsForms, anditshouldnotbeusedifyoudon’thaveaveryspecificneedforit.
- DockPanel:Definesanareawherethepositionofacontrolisrelativetothe positionofanotherchildcontrolinthesamecontainer.Thepossibledock positionsareTop,Right,Bottom,andLeft.InWPFthereisnotaFillpositionlike inWindowsForms.
- Grid:Definesatable-stylecontainerwithrowsandcolumnsandactslikean
HTMLtablewhereyoucanspancontrolsacrossmultiplerowsandcolumns.
- StackPanel:Acontainerthatstacksthecontrolsverticalorhorizontaloneafterthe otherone.Youcandefinethespacebetweeneachcontrol.
- WrapPanel:Positionschildelementsinsequentialpositionfromlefttoright, breakingcontenttothenextlineattheedgeofthecontainingbox.
InWPFyouhavethesamelayoutlogicdescribedinHTMLbytheboxmodeltechniquewhereeach controlhasaMarginpropertyandeachchildhasaMarginpropertyandaPaddingproperty.
Margindefinesthespacebetweenanelementanditschildelements.Paddingdefinesthespace
betweenachildelementanditsparentcontainer.Themaindifferencebetweenthetwopropertiesis thatMargingivesyouspaceoutsidethecontrol,andPaddinggivesyouspaceinsidethecontrol. AdditionalpositionpropertiesareHorizontalAlignmentandVerticalAlignment,whichareusedto specifyadefaultpositionofacontrolinthecontainer. Figure1-3showsasummaryoverviewofthepositiontechniquesinWPF.
Figure1-3.WPFcontrolspositionoverview
CommonControls
WPFoffersasetofcommoncontrolsavailableintheVisualStudiotoolboxthatcanbeusedforyour dailyactivitieswithouttheneedofwritingadditionalcode.Insomecases,youmayneedtocustomize theappearanceofacontrolortochangethebehaviorofacontrolusingthestylesandthetemplates.
Inothercases,youmayneedtolistenforaneventofacontrolinordertoexecuteaspecificcode;for example,youmayneedtolistenfortheClickeventofaButtoncontrolinordertoexecuteaspecific operation.
AllthesestepscanbeaccomplishedusingtheXAMLmarkuporbywritingcode-behindtheXAML;it dependsonwhatyouaredoingandhowyouaredoingit.Inthissection,youwillseetheavailable controlsprovidedbyXAML,andinthenextchapters,youwillseehowyoucancustomizethedefault appearanceandthedefaultbehaviorsofacontrol.
Control Composition
EachcontrolthatinheritsfromthebaseclassSystem.Windows.Controls.Controliscomposedbya defaultsetofcomponentsthatyoucancustomizeandchangeusingtheStyleTemplateorthe
DataTemplate.TheclassControliscomposedbyaControlTemplate,whichrepresentsthedefault
templatefortheappearanceofthecontrolintheUI;whenyoucustomizetheDataTemplateofacontrol, youchangehowtheControlTemplateshouldbehave. TheControlTemplatemaydisplayasingleitem,acollectionofitems(likeaListBox),oraHeaderof anitem;forthisreason,inWPFyouhavecontrolsthatareoftypeContentControl,ItemsControl,or
HeaderControlbasedonhowtheControlTemplateshouldbestructured.
VisualStudioandthe.NETFramework4provideasetofdefaultcontrols,detailedinthefollowing list.Ifyouwanttogetamoredetailedexplanation
en-us/library/system.windows.controls.aspx,inparticulartothesection“System.Windows.Controls”
whereyouwillfindthecompletelistofavailablecontrols. Thefollowingarethecategoriesofavailablecontrolsin.NET4;theyrepresentonlypartofthefull setofcontrolsdeliveredwiththe.NETFramework4.
- Buttons:ThisrepresentsaButtonwithalabelorcomplexcontent.
- Inputs:TextBlockandTextBoxarepartoftheavailableinputcontrols;thefirst controlcanbeusedasaLabel,whilethesecondcontrolisusedtoretrieveor displaytextintheUI.
- List:GridView,ListBox,ComboBox,andItemsControlarecontrolsabletodisplay andselectitemsinalistofitems.
- Layout:Thissectionconsistsofallthecontrolsdesignedtocontainandprovide layouttochildcontrols,suchasStackPanel,DockPanel,andsoon.
- Documents:Thesearecontrolsdesignedforinteractingwithdocumentssuchas
XPSdocuments. AsIsaidpreviously,everyoneofthesecontrolscanbeaddedtotheUIusingtwodifferent approaches:youcandeclarethecontrolbyusingXAMLorbywritingC#codeandaddingthecontrolto thecontrolscollectionoftheparentcontainer.Listing1-7showsthetwomethods.
Listing1-7.ExampleofCreatingaControlwithXAMLorwithC# <!-- using XAML --> <StackPanel Name="pnl"> <Button Name="btnFirst" Content="First" /> </StackPanel>
// using C# StackPanel pnl = new StackPanel(); Button ctrl = new Button(); ctrl.Name = “btnFirst”; ctrl.Content = “First”; this.pnl.Controls.Add(ctrl); WPFArchitecture
WindowsPresentationFoundationisacomplextechnologythatconsistsofasetofbaseassembliesplus asetofadditionalassembliesusedintheUI. ThetwoprimaryassembliesthatcontainmostoftheWPFcodearePresentationCoreand
PresentationFramework.PresentationCorecontainsthecorecodeforWPFandallthebaseclasses,while