• LearnXAML(theExtensibleApplicationMarkupLanguage)through • SeehowtointegrateWindowsForms,DirectX,ActiveX,orothernon-WPF • DiscoverhowtointegrateWPFwithreportwriterssuchasCrystalReports andSQLServerReportingServices.
iv
Contents at a Glance
AbouttheAuthor...xii
AbouttheTechnicalReviewer...xiii
Acknowledgments...xiv
Introduction...xv
■
Chapter1:IntroducingWPFandXAML...1
■
Chapter2:SampleApplication:OverviewandGettingStarted...25
■
Chapter3:MicrosoftExpressionBlend...43
■
Chapter4:CreatingtheViews...61
■
Chapter5:AddingControlstotheViews...87
■
Chapter6:TheEntityFramework...113
■
Chapter7:DataBinding...159
■
Chapter8:CommandHandlingandEventRouting...189
■
Chapter9:TestingwithTDD...209
■
Chapter10:ReportswithMicrosoftReportingServices...227
■
Chapter11:DeploytheApplicationUsingClickOnce...251
■
Chapter12:DesignPatternsinWPF...261
■
Chapter13:WPFandMultithreading...275
■
Chapter14:InteractingwithWCF...289
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.
xvi
DownloadingtheCode
Thesourcecodeforthisbookisavailabletoreadersatwww.apress.comintheDownloadsectionofthe book’spage.PleasevisittheApresswebsitetodownloadallthecode.Youcanalsocheckforerrata,and findrelatedApresstitles.
ContactingtheAuthor
Youarewelcometocontacttheauthor,RaffaeleGarofalo(akaRaffaeu),withquestions.Youcanreach himatraffaeu@raffaeu.comoryoucancontacthimbyvisitinghttp://blog.raffaeu.com.
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.
2
■
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"> <Grid>
</Grid> </Window>
TherootelementintheListing1-2containstheattributesxmlnsandxmlns:x.Theseattributes indicatetoaXAMLprocessorwhichXAMLnamespacescontainthetype.Thexmlnsattributespecifically indicatesthedefaultXAMLnamespace.Thexmlns:xattributeindicatesanadditionalXAMLnamespace, whichmapstheXAMLlanguagenamespace(whichishttp://schemas.microsoft.com/winfx/2006/xaml). ThenamespacedeclarationalwaysappliestoallthedescendantelementofaXAMLdocument,just astheydoforanXMLdocument;forthisreason,youwon’tneedtodeclarethesamenamespacetwice inaXAMLdocumentinordertouseitstypes,butyouwillneedtodeclarethosetypesprecededbythe correspondingelementprefix.
Youmayalsoneedtoreferenceacustomtypeprovidedbyanamespacethatyouhavepreviously createdandthatisalreadyreferencedinyourXAMLapplication;todothat,youshouldusethekeyword
xmlnsfollowedbyyourcustomprefixandthenaddareferencetothenamespacecontainingtheclasses youwanttouse.
Listing1-3.XAMLfilewithcustomreferences
<Window
x:Class="Chapter01.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 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" />
4
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
{
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" />
6
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.
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.
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:
http://msdn.microsoft.com/en-us/library/ms788723.aspx.
Introduction to WPF
WPFistheMicrosoftXAMLtechnologyforclientapplicationshostedonaWindowsoperatingsystem. ThecurrentversionofWPFisthe4.0,whichisdeliveredwiththe.NETFramework4.
WPFisavectorialUItechnologythatusesXAMLasamarkuplanguagetodefinetheUIandusesC# orVB.NETforthepresentationlogic.
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
(www.codeplex.com),whereyoucanfindhundredsoffreecontrolsandcontainersforyourWPF
applications.Inthisbook,youwillusesomeofthesecontrolstobuildanOffice-styleapplication. YoucanaddWPFcontrolstotheviewusingtheXAMLmarkuplanguageoratruntimeusingthe code-behindfile;youmayneedtocreateaparticularUserControlthatwillneedtocreatechildcontrols
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.
■
NoteWiththeterm
view
,wedefineanyUIcontainersuitabletoofferagraphicalrepresentationofthedataand
aninteractionbetweentheapplicationandtheuser.InWPFaviewcanbeawindow,amodaldialog,orasimpler
usercontrol.
WithWPFyouhavedifferentwaysofpilingthecontrolsinacontaineranddifferentwaysofresizing thecontrolsinthecontainerwhenthecontainersizechangesorwhenthescreenresolutionsize changes.TheinterestingnewsisthatwithWPFyoudon’tneedanythingelsetoprovidethecodeforthe resizingprocessbecausethecontrolscontainerisinchargeofthat.
Layoutcontainershavedifferentbehaviors:
• Canvas:Definesanareawhereeachchildcontrolispositionedbyprovidingan absolutecoordinatesvalue.ThisisthesamebehavioryouhadinWindowsForms, anditshouldnotbeusedifyoudon’thaveaveryspecificneedforit.
• 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.
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.Ifyouwanttogetamoredetailedexplanationofeachcontrol,refertohttp://msdn.microsoft.com/
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">
// 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 thePresentationFrameworkassemblycontainsalltheconcretecontrolsusedintheUI.Thethird componentismilcore,whichstandformediaintegrationlayerandistheunmanagedpartofWPFin chargeoforchestratingtheUIinteractionsuchasanimations,hardwareperformances,andDirectX.
Figure1-4showsthestructureofWPFinthe.NETFramework(theimageistakenfrom
msdn.microsoft.comintheOfficialWPFsection);thePresentationFramework,PresentationCore,and milcoresectionsarethefoundationofWPF.
Figure1-4.WPFarchitecture
Assemblies and CLR
redirectthecalltotheUIthread.TheDispatcherprovidedinthisnamespaceisinchargeofsolvingthis problem.
System.Windows.DependencyObjectisanotherclassfundamentalinWPF;itenablesthetracking
processofthedependenciesofapropertyofaXAMLobject.Forexample,whenyoudatabindanobject toaview,inXAMLDependencyObjectactsasamediatorbetweentheviewandtheBindobjectand notifiesthetwoactorswhensomethingchanges.
System.Windows.Media.VisualisthenamespaceinchargeofcontrollingthewaytheUIisdesigned andthewaythepixelsarerenderedonthescreen.Thisassemblyisnotuseddirectlybyyou,butitis usedindirectlywhenyoucreate,forexample,anewcontrolintheUI.
InSystem.Windows.UIElement,youcanfindeverythingrelatedtolayout,input,andevents.Inthe layout,asyousawintheprevioussection,youwillfindallthecontrolsinchargeofarrangingthe elementsintheUI;intheinputandevents,youwillfindallthosemethodsusefultocontroltheuser interactionsuchasMouseClickorSelectionChanged.
InSystem.Windows.FrameworkElement,youcanfindpartoftheUIpropertiesusedtomanagethe layout,suchasHorizontalAlignmentandVerticalAlignmentforexample,orthedatabindingengineand thestyles.
Finally,System.Windows.Controlsisthenamespaceinchargeofprovidingeverythingforthe creationofUIcontrols;italsocontainsalltheUIcontrolsshippedwithWPF4.
ThesearethenamespaceavailableinWPFthatprovideallthetoolsandmechanismstomakea consistentandpowerfulWPFapplication;inthecourseofthisbook,youwillseewhenandhowtouse mostofthem.
Technologies
Intheprevioussection,yousawthatWPFshipswithasetofassemblies,andeachoneprovidesoneor moreWPF-relatedtechnologiessuchasstyles,databinding,commanding,andmore.Inthissection, you’llgetanoverviewofthetechnologiesprovidedwiththissetofassembliesandhowtousethemand, morethananythingelse,whytheyareuseful.
Styles
IfyoueverworkedinthepastwithanywebtechnologysuchasASP.NET,PHP,JSP,orevenasimple HTMLwebpage,youmayknowthateverypartofawebpagecanbestyledusingCascadingStyleSheets (CSS).Inthisway,youcancreateaUIstyletorepresentaTextBoxinaparticularway,andthisstylewill bespreadalloveryouwebapplication.
IfyoueverworkedbeforewithaclienttechnologysuchasWindowsFormsorJavaForms,youmay knowthatthisisanimpossibletasktoachieveusingthebasictoolsprovidedbythesetwoframeworks. WhatImeanisthatinWindowsForms,youcan’tdefineastyleforaUIcontrol;youneedtocreatea specificUIcontrolthathasthestylehard-codedinthebaseclass.Forexample,ifyouwantanice
TextBoxwithaspecificbordercolorandaspecificbordershape,inWindowsFormsyouhavetocreatea customTextBox.
InWPFyouhavethestyleslikeyouhaveontheWeb,butprobablywithalotmorepowerand control.Inastyleyoucansetstaticvaluesordynamicvaluesusingtriggers;forexample,youmayhavea
TextBoxstylethatdefinesthebackgroundcolortowhite,butwhentheTextBoxgetsthefocus,the backgroundbecomesyellow.
Listing1-8.ComparisonBetweenEmbeddedSetterorStyle
<StackPanel Name="pnl"> <StackPanel.Resources> <!-- TextBox style -->
<Style TargetType="TextBox" x:Key="TxtStyle"> <Setter Property="FontFamily" Value="Verdana" /> <Setter Property="Background" Value="Yellow" /> <Setter Property="Width" Value="200" />
</Style>
</StackPanel.Resources>
<!-- TextBox with embedded style --> <TextBox Width="200" Height="25" FontFamily="Tahoma" FontSize="12" />
<!-- TextBox with associated style --> <TextBox Style="{StaticResource TxtStyle}" /> </StackPanel>
Inthesecondcase,youcaneasilyrecycleandapplythepropertyStyle="{StaticResource TxtStyle}"toanyTextBoxandspreadyourstyleallovertheapplication.
Theonlyconstraintyouhavewhenyouprepareastyleforaspecificcontrolisthatthestylemustbe foraspecificcontrol,andtodothat,youmustprovideavalueforthepropertyTargetTypeoftheStyle element;inthisproperty,youhavetospecifythecontrolyouarestyling.
Additionalconsiderationhastobedonetothex:Keyattachedproperty.Ifyouspecifyakey,you mustprovidethatkeyoneverycontrolthathastousethestyle;otherwise,youcanavoidspecifyinga valueforthex:Keypropertysothatanycontrolofthattypewillusethestyle.
DataTemplates
AnotherwaytocustomizethelayoutofyourcontrolsisusingtheDataTemplates.ADataTemplateisthe templatethatrepresentsthedataexposedbyyourcontrol.UsuallyyouworkwithaDataTemplatewhen youwanttocustomizehowanItemsControldisplaysitsitemsatruntime,butyoucanusethe
DataTemplatealsotocustomizeacontrolthatdisplaysasingleitem.Usually,anItemsControl,likea
ListBox,displaysthe.ToString()methodoftheitemsboundtoitintheUI,sowhenyoutrytobinda listofobjectstoaListcontrol,youwillgetaweirdresult,andtheonlypropertyavailabletocustomize thedatayouaredisplayingistheDisplayMemberPath,whichallowsyoutopromptonlyonepropertyby usingastringformat.IfyoucustomizetheDataTemplateofyourListBox,youwillbeabletovisualize theitemsboundtothecontrolasyouwantthem;forexample,youmayforcetheListBoxtodisplayfor eachrowtheFirstNameandtheLastNameofaPersonclassinaStackPanelusingtwoTextBlockcontrols.
Figure1-5showsascreenshotofVisualStudio2010;inthefigurethereisaUserControlwithtwo
Figure1-5.DifferencesbetweenListBoxwithandwithoutaDataTemplate
Likewithstyles,youcanaddadatatemplateinsideanelementlikeinthefollowingcode:
<DataTemplate>
<StackPanel Margin="3" Orientation="Horizontal"> <TextBlock
<!--
Bind the Firstname property using the String.Format method that will display "Name: [FirstName]"
-->
Text="{Binding Path=FirstName, StringFormat=Name: {0}}" Margin="0,0,5,0" /> <TextBlock
Text="{Binding Path=LastName}" Margin="0,0,5,0" /> <TextBlock
Text="{Binding Path=DateOfBirth, StringFormat=Birth: {0:d}}" /> </StackPanel>
</DataTemplate>
■
NoteOfcourse,ifyoubelievethattheDataTemplatewillbeusedinthefuturebyanothercontrol,Ikindly
suggestyoucreatefromthebeginningaresourcedictionaryfileinyourapplicationwithalltheDataTemplatesyou
willuse.Thiswillsavealotoftime!
DataBinding
DataBindingisanotherpowerfulfeatureofWPF,andit’sprobablythemostdesirablefeatureofthis technology,whichmakesWPFsopowerfulandflexible.
InWPFandalsoinSilverlight,DataBindingistheprocessthatallowstheUItobeboundtothe applicationdataandmakeboththeUIandthepresentationlogicawareofchangesintheoriginaldata orintheUI.InWPF,mostoftheavailableUIcontrolshaveanin-placebindingmechanismthatallows youtobinddynamicdatatotheUI.
Ifyouthinkforamomentaboutanormalline-of-business(LOB)application,youwillfindthatthe mainprocessiscomposedofthreesimplesteps:retrievethedatafromthedatabase,displaythedatain theUI,andupdatethedatabasedonactionstheuserdidintheUI.Allthesestepscanbeeasily accomplishedifyouwritethecorrectpresentationlogicandbindittoaWPFcontrol.
Thistopicinconjunctionwiththe“StylesandTemplates”sectionwillbeanalyzedindepthinthis bookinChapters5and7whereyouwilllearnhowtocreateacoolUIandhowtoapplystylesand DataTemplatetotheUI.
WPF4Tools
WPFisanicetechnology,butitisbasedonacombinationoftwoprogramminglanguages—XAML markupandthelanguageyouchooseforthecode-behindfile,whichC++,C#,orVB.NET.Withsome effort,youshouldbeabletowriteandcompileanentireWPFapplicationjustbyusingtheclassic NotepadapplicationandthepropercompilerinaCommandPromptwindow,butatthesametimeI canguaranteeyouthatitwillbeaverychallengingexperienceforeventhemostexpertWPFdeveloper.
Fortunately,MicrosoftprovidesasetoftoolstodevelopWPFapplications,whichwillmakeyourlife mucheasier;thesetoolsaretargetedtodifferentaudiences,soyoushouldfindonetowritethe
presentationlogicandonethatismorefeasibleforadesigner.
Mostofthesetoolsareunderlicense,soyouwillnotfindthemforfreeontheInternet,but Microsoftoffersabasicsetofthesetoolscalledexpresseditions,whichareavailableforfreebutwitha limitedsetoffunctionalities.
Finally,therearealsofreetoolsavailableforWPFdesigners,whichcanmakeyourlifemucheasierif youneedtotestyourWPFresultintheUIwithoutrunningaWPFapplication;thesetoolsareusually usedtotesttemplatesandstylesbeforetouchingtheproductioncode.
Visual Studio 2010
MicrosoftVisualStudio2010isbuiltontheWPFtechnology,soit’sprobablythemostfeasibletoolto buildWPFapplications.Itisdeliveredinthreeversions:
• Professional:TheperfectversionifyouarestartingtodevelopWPFapplication andyouarestillnotsureitwillbeyourfinalchoice
• Premium:ThericherversionifyouarealreadyworkingwithWPFandyoualso needtosharethecodeonyourteamandtestit
• Ultimate:TherichestversionofVisualStudiousedusuallybyseniordeveloper, softwarearchitects,andQA
• TestProfessional:AnintegratedtestingtoolsetversionofVisualStudio
Youcandownloadeachoneoftheseversionsonyourcomputerandtryitfor90dayswithout buyingthefinalproduct.
Ifyoucan’taffordalicenseofVisualStudio,thereisstilltheoptionofdownloadingandusingthe expressversionofVisualStudioavailableatwww.microsoft.com/express/.TheexpresseditionsofVisual Studioaredividedbytopic,soyouwillfindanexpresseditionforVisualC#,oneforVisualC++,onefor VB.NET,oneforwebdevelopment,andoneforWindowsphonedevelopment.
WhenyouopenVisualStudioandyouchoosetocreateanewWPFapplication,youwillbe promptedbyVisualStudiotochoosefromoneoftheavailablesolutions:
• WPFApplication:Thisistheclassicstand-aloneapplicationthatwillresultina final.exefilethatcontainsallthecodegeneratedintheproject;thisapplication canbeexecutedinanyWindowsOSthathasthe.NETFramework4orNET3or 3.5.
• WPFBrowserApplication:ThisisthewebversionofWPF,whichwillproducean
.xbapfilethatcontainsallthecodegeneratedintheproject;thisapplicationcan beexecutedinInternetExplorer.
• WPFCustomControlslibrary:Thisisaseparateassembly(.dll),whichcontains customcontrols.CustomscontrolsareusuallyenhancementofexistingWPF controls.
• WPFUserControlsLibrary:Thisisaseparateassembly(.dll),whichcontains user-createdcontrols;inthislibrary,youwillcreatecontrolsthatdonotexistin WPF.
Figure1-6.NewProjectdialogboxinVisualStudio2010
AfteryouchoosewhichsolutionyouwanttocreateinVisualStudioandselectanameanda destinationfolder,VisualStudiowillcreateforyouafolderwiththenameofyoursolution,asolutionfile (.sln)thatcontainsallthecodethatdescribesthesolutionfolderstructure,andaprojectfilethatwill describethecurrentproject,inmycaseaWPFapplication.
Figure1-7.WPFapplicationinVisualStudio2010
VisualStudioiscomposedbyasetofdockablepanels;dockablemeansyoucandraganddropany panelofVisualStudioanddecidewheretostickitintheIDE.Ifyoudragapanelinasectionthat containsalreadyotherpanels,thepanelbecomesatabbedpanel.
Figure1-7showsaWPFapplicationopeninVisualStudio;therearefivemajorsections,whichshow youhowVisualStudiohandlesthedockablepanels.
• 1,thetoolbarandmenubar:InthissectionofVisualStudioyouwillfindallthe availablecommandsandmenus.Usingtheright-clickmenu,youcanchoose whichmenutoshowintheIDE.
• 2,leftside:Bydefault,theleftsideofVisualStudioshowstheToolboxofavailable WPFcontrolsandtheServerExplorerpanel.
• 3,centerpanel:Thecenterpanelshowstheopenfilesinatabbed-styleUI.
• 4,rightside:IntherightsideofVisualStudioyouusuallyhavetheSolution Explorer,whichdisplaysthestructureofyourapplication,andapanel,which showsthepropertiesofthecurrentobjectselectedinthecenterpanel.
• 5,splitpanel:InVisualStudioyoucanuseonesectionoftheUItosplitpanelsso thatyoucanhaveastackofpanelsallinonepartoftheIDE.
separateUIs.ThesetwoviewscanbeswitchedinVisualStudio,andassoonasyoumakeachangein oneofthem,theotheroneneedstoberefreshedinordertoshowyouthefinalresult.Ifyouwanttoview thecode-behind,yousimplyneedtoright-clickanypartoftheXAMLfileandselectViewCode.
Expression Blend
ExpressionBlendisoneoftheproductsavailableinsetoftoolscalledExpression,andit’savailablefor downloadatwww.microsoft.com/expression/.ExpressionBlendisdeliveredinapackagethatis composedofvarioustoolsusedbydesignerstocreateimages,websites,video,andUIsforWPFor Silverlight.ExpressionBlendcanbeconsideredtheVisualStudioforWPFandSilverlightdesigners; althoughExpressionBlendisstillagoodtoolforcoding(becauseitallowsyoutoeditXAMLcodeandC# orVB.NETcode-behindfiles),itsaudienceismoreadesigneraudiencethanadeveloperaudience.
YoucanopenandeditanexistingVisualStudio2010solutionusingBlendsothatyoucan customizeandtestyourUIstylesandthenreopenthesolutioninVisualStudiotofocusmoreonthe presentationlogic;inthesameway,youcanopenpartofyourfilesinVisualStudio(developer)andpart inBlend(designer)sothattwopeoplecanworkonthesameprojectandfocusondifferentareas,like thedesignandthepresentationlogic.
WhenyouopenExpressionBlend(Figure1-8),youarepromptedtocreateanewproject(Figure1-9)ortoworkwithanexistingtemplateprovidedbyMicrosoftbydefaultinBlend.
Figure1-8.ExpressionBlendstartpage
Figure1-9.ExpressionBlend’sNewProjectwindow
TheonlydifferencebetweentheprojectsyoucancreateinVisualStudioandtheonesyoucan createinBlendisthenewWPFDataboundApplication,whichisaWPFapplicationthatusestheModel ViewViewModel(MVVM)patterntoseparatetheUIlogicfromthepresentationlogic.Youwillseethis patternindetailinChapter12.
ExpressionBlendisanawesometooltocreateandcustomizerichUIsforWPF,anditisagreattool tolearntheXAMLsyntax;whileyoudraganddropcontrolsandstylesintheBlendIDE,youcanswitch totheXAMLcodeandtakealookonhowthestylesyouarecreatingworkinXAML.
Additional Tools
SometimesyoumayneedtotweakjustapieceofXAMLcodeandyoudon’twantoryoucan’topenand createanewsolutioninVisualStudioinordertodothat.Inothersituations,youareexperimentingwith anewsetupofavieworusercontrol,butyoudon’twanttoscrewupthecurrentproject,soyouneeda quickandfastwaytocreateanewWPFapplicationandplaywithadummyXAMLfile.
• XAMLPAD:ThisXAMLeditorisdeliveredwithBlendandVisualStudioSDK;it’s availablefordownloadathttp://msdn.microsoft.com/en-us/library/
ms742398(v=vs.90).aspx.ItisagreattooltoeditandstyleXAMLfiles,butit doesn’tallowyoutoeditcode-behindfiles.
• KAXAML:ThisisanalternativeXAMLeditorthatyoucandownloadforfreeat
www.kaxaml.com.Ithas,moreorless,thesamecharacteristicsofXAMLPad.
AnotherinterestingtoolthatcomeswiththeVisualStudioSDKisUISpy.exe,whichallowsyoutospy onrunningapplicationsinordertoviewwhethertheirstructureisconformingtoyourrequirements.
XAMLPowerToysareaVisualStudioextensionthatenablesamorecontext-sensitiveXAML IntelliSensewhileyouareworkingwithyourWPFapplications.Itallowsyoutosearchandfilterspecific keywordswhileyouareworkingintheVisualStudioIDEwithoutinterferingwiththedefault
IntelliSense.
Summary
XAMLisapowerfulmarkuplanguageavailableinthe.NETFramework4tocreaterichinterfacesand applications.Itisusedbythreedifferenttechnologiesavailableinthe.NETFramework:Windows PresentationFoundation(WPF),Silverlight(SL),andWorkflowFoundation(WF).
ItisstructuredusingtheXMLdefinition,anditreflectstheXMLspecificswhereonlyoneelement candefinetherootelementofthefileandwhereyoucaneditpropertiesusingattributesorchild elements.
Inacodefile,youcanfindtheproceduralcode,whichcanbeVB.NETorC#,inafilecalleda code-behindfilethathasthesamenameasyourXAMLfileplusafileextensionbasedonthe.NETlanguage theapplicationisdonein(suchas.csforC#and.vbforVB.NET).
WPFistheclient-sidetechnologyprovidedbythe.NETFramework;itisbuiltontwomajor
assemblies:PresentationCoreandPresentationFramework.ItisavectorialUItechnology,whichmeansit isabletoadapttothedifferentscreenresolutionswithoutlosingqualityandcanbeexecutedasastand-aloneapplicationorasabrowserapplicationwithinInternetExplorer.
WPFprovidestwopowerfultechnologieswithit;oneisthestyleandtemplate,whichallowsyouto totallycustomizehowyourUIbehave,andoneistheDataBinding,whichisapowerfuldata-binding engineprovidedinalmosteveryUIcontrol.
■ ■ ■
Sample Application: Overview
and Getting Started
ThisbookispartoftheApressseriescalledInContext;inthisspecificcase,youwillseehowWPF4can beappliedincontext.Butwhatdoesincontextmean?Theseriesfocusesondeliveringacompleteguide toatechnology(inthiscaseWPF4)bybuildingareal-worldapplicationviatutorials.Ibelievethattrying atechnologyisthebestwayoflearningandmasteringit.
Theapplicationyouwilldevelopinthisbookisatime-trackingapplicationthatwillbeusedtotrack thetimespentbyACMEConsultingLtd.employees.ACMEConsultingLtd.isafakeITconsulting companythatwillbeyourcustomer.Bytheendofthebook,youwillhaveacompletetime-tracking applicationdevelopedinWPF4thatyouwillbeabletodeployandreleaseorthatyoucanuseasaroad mapforanyfutureclientapplicationyoudevelopusingWPF4.
Inthischapter,youwilllearnabouttherequirementsforexecutingthecodeandsamplesinthis bookandwhatsoftwaretoolsyoumayneedtowriteamorefashionableUI;everythingneededinthe bookisavailablethroughdownloads.You’llfindthesourcecodeatApress.com;therestofthe downloadslinkswillbeprovidedinsidethebook.
Requirements
ApressTimeTracker(ATT)isaWPF4clientapplicationthatusesanIISwebserverandaSQLServer2008 R2Expressdatabaseserverasitsdatastore.InATTyouwillusealsosomeroyalty-freeUIcontrolsand icons,whichyoumaywanttopurchaseifyourfinalresultwillbeacommercialproduct.
Ihavedividedthesoftwarerequirementsintotwosections.Thefirstoneisalistofsoftwareand third-partytoolsusedinthisbookthatmaynotbefree,andthesecondpartincludesopensource projectsfreeofchargethatyoumaywanttouseinyourproject.
ToolsandSoftware
• MicrosoftVisualStudio2010:TheversionofVS2010usedinthisbookisthe Expressversion.Ifyouwanttobeabletoopenandmodifythefilesthat
accompanythisbook,includingUMLdesignfilesandschema,youmayconsider downloadingtheExpresseditionofVisualStudio2010forVisualC#at
www.microsoft.com/express/Downloads/#2010-Visual-CS.Youcanalsodownloada
trialversionofVisualStudio2010UltimateorPremiumversionorpurchasea license.AtrialversionofVisualStudio2010isalsoavailableatwww.microsoft.com/ visualstudio/en-us.
• MicrosoftSQLServer2008R2Express:MicrosoftSQLServer2008R2Express editionisavailableinalotofdifferentversions;theoneusedinthisbookisthe ExpressionVersionwithAdvancedService,whichisavailableforfreeat
www.microsoft.com/express/database/.Itincludeseverythingyouneedtobuilda robustdatabaseincludingReportingServices.
IconsandTemplates
YoucanfindalotoffreeiconsandWPFtemplatesontheWeb.Justtogiveyouanexample,inthis applicationIusediconsandimagesfoundviatheiconsearchenginewww.iconfinder.com;ifyouplanto usegraphicalimagesinacommercialapplication,youmustverifythepermissionsandanypotential royaltypaymentsrequiredfortheuseofthoseimagesbeforeincludingtheminyourapplications.
Thethemesusedonthisbookareavailableforfreeatwww.codeplex.com,whichisthebiggestopen sourceportalfor.NETapplications;thethemesaredownloadablefromhttp://wpfthemes.
codeplex.com/.
Third-PartyLibraryandControls
Youcanalsousesomethird-partytoolsandlibrary,whichwillmakeyourjobeasier.Partsofthese librariesareopensource,andtheyarenottheonlyonesavailablethroughtheinternet.Feelfreetouse themortodownloadadifferentoneassuggestedinthebook.
• EnterpriseLibrary5.0:TheEnterpriseLibraryisahuge.NETapplication
frameworkthatgivesyouadditionalcapabilitieswhenworkingwithyourcode.It includesanInversionofControlframework,validationblock,logging,exception handler,andmore.Itisavailableathttp://entlib.codeplex.com/.
• AutoMapper:AutoMapperisanopensourceframeworkbuilton.