Ch7.2-Controls for Programm 001-193819qk

romoeogonzales 11 views 53 slides Oct 05, 2024
Slide 1
Slide 1 of 53
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53

About This Presentation

This is the controll


Slide Content

Controls
CHAPTER 8.2

What you willlearninthis chapter
Content controls. These controls can contain nested elements, giving them nearly
unlimited display abilities. They include the Label, Button, and ToolTip classes.
Headeredcontent controls. These are content controls that allow you to add a
main section of content and a separate title portion. They are usually intended to
wrap larger blocks of user interface. They include the TabItem, GroupBox, and
Expander classes.
Text controls. This is the small set of controls that allow users to enter input. The text
controls support ordinary text (the TextBox), passwords (the PasswordBox).
List controls. These controls show collections of items in a list. They include the
ListBoxand ComboBoxclasses. Range-based controls. These controls have just one
thing in common: a Value property that can be set to any number in a prescribed
range. Examples include the Slider and ProgressBarclasses.
Date controls. This category includes two controls that allow users to select dates:
the Calendar and DatePicker.

What you willlearninthis chapter
ListView. The ListViewderives from the plain-vanilla ListBox. It adds support for
column-based display and the ability to switch quickly between different “views,”
or display modes, without requiring you to rebind the data and rebuild the list.
TreeView. The TreeViewis a hierarchical container, which means you can create a
multilayereddata display. For example, you could create a TreeViewthat shows
category groups in its first level and shows the related products under each
category node.
DataGrid. The DataGridis WPF’s most full-featured data display tool. It divides your
data into a grid of columns and rows, like the ListView, but has additional
formatting features (such as the ability to freeze columns and style individual rows),
and it supports in-place data editing.

What you willlearninthis chapter
Menus. They’re one of the oldest user interface controls, and they’ve changed
surprisingly little in the past two decades. WPF includes solid, straightforward
support for main menus and popup context menus.
Toolbars and status bars. They decorate the top and bottom of countless
applications—sometimes when they aren’t even needed. WPF supports both
controls with its customary flexibility, allowing you to insert virtually any control
inside. However, the WPF toolbars and status bars don’t have many frills. They
support overflow menus, but they don’t provide floating and docking capability.
Ribbons. With only a little more effort, you can add an Office-style ribbon to the
top of your application window. It requires a separate (free) download, but you’ll
get some valuable built-in features, such as configurable resizing. You’ll also get an
Office-style menu feature to match.

TheListViewisaspecializedlistclassthat’sdesignedfordisplayingdifferentviews
ofthesamedata.TheListViewisparticularlyusefulifyouneedtobuildamulticolumn
viewthatdisplaysseveralpiecesofinformationabouteachdataitem.
TheListViewderivesfromtheListBoxclassandextendsitwithasingledetail:the
Viewproperty.TheViewpropertyisyetanotherextensibilitypointforcreatingrichlist
displays.Ifyoudon’tsettheViewproperty,theListViewbehavesjustlikeitslesser-
poweredancestor,theListBox.
ViewpropertypointstoaninstanceofanyclassthatderivesfromViewBase
(whichisanabstractclass).TheViewBaseclassissurprisinglysimple;infact,it’slittle
morethanapackagethatbindstogethertwostyles.OnestyleappliestotheListView
control(andisreferencedbytheDefaultStyleKeyproperty),andtheotherstyle
appliestotheitemsintheListView(and isreferenced by
theZItemContainerDefaultStyleKey property). The DefaultStyleKey and
ItemContainerDefaultStyleKeypropertiesdon’tactuallyprovidethestyle;instead,
theyreturnaResourceKeyobjectthatpointstoit.
THE LISTVIEW

Viewpropertyisausefulabstractionofitsadvantages:
Reusableviews.TheListViewseparatesalltheview-specificdetailsintooneobject.
Thatmakesiteasiertocreateviewsthataredata-independentandcanbeused
onmorethanonelist.
Multipleviews.TheseparationbetweentheListViewcontrolandtheViewobjects
alsomakesiteasiertoswitchbetweenmultipleviewswiththesamelist.(For
example,youusethistechniqueinWindowsExplorertogetadifferentperspective
onyourfilesandfolders.)Youcouldbuildthesamefeaturebydynamically
changingtemplatesandstyles,butit’seasiertohavejustoneobjectthat
encapsulatesalltheviewdetails.
Betterorganization.Theviewobjectwrapstwostyles:onefortherootListView
controlandonethatappliestotheindividualitemsinthelist.Becausethesestyles
arepackagedtogether,it’sclearthatthesetwopiecesarerelatedandmayshare
certaindetailsandinterdependencies.Forexample,thismakesalotofsensefora
column-basedListView,becauseitneedstokeepitscolumnheadersandcolumn
datalinedup.
THE LISTVIEW

CreatingColumnswiththeGridView
TheGridViewisaclassthatderivesfromViewBaseand
representsalistviewwithmultiplecolumns.Itdefinethose
columnsbyaddingGridViewColumn objectstothe
GridView.Columnscollection.
Figure22-1showsastraightforwardexamplewiththree
columnsofinformationaboutaproduct.
THE LISTVIEW

CreatingColumnswiththeGridView
THE LISTVIEW

ResizingColumns
Formoremicromanaged controlover
columnsize,youcansetaspecificwidth
whenyoudeclarethecolumn:
THE LISTVIEW

CellTemplates
TheGridViewColumn.DisplayMemberBindingpropertyisn’ttheonlyoption
forshowingdatainacell.YourotherchoiceistheCellTemplateproperty,
whichtakesadatatemplate.Thisisexactlylikethedatatemplatesyou
learned,exceptitappliestojustonecolumn.Ifyou’reambitious,youcangive
eachcolumnitsowndatatemplate.
Celltemplatesareakeypieceofthepuzzlewhencustomizingthe
GridView.Onefeaturethattheyallowistextwrapping.Ordinarily,thetextina
columniswrappedinasingle-lineTextBlock.However,it’seasytochangethis
detailusingadatatemplateofyourowndevising:
THE LISTVIEW

CellTemplates
THE LISTVIEW

CreatingCustomView
IftheGridViewdoesn’tmeetyourneeds,youcancreateyourownviewtoextend
theListView’scapabilities.Unfortunately,it’sfarfromstraightforward.
Tounderstandtheproblem,youneedtoknowalittlemoreaboutthewayaview
works.Viewsdotheirworkbyoverridingtwoprotectedproperties:DefaultStyleKey
andItemContainerDefaultKeyStyle.Eachpropertyreturnsaspecializedobjectcalled
aResourceKey,whichpointstoastylethatyou’vedefinedinXAML.The
DefaultStyleKeypropertypointstothestylethatshouldbeappliedtoconfigurethe
overallListView.ThetemContainer.DefaultKeyStylepropertypointstothestylethat
shouldbeusedtoconfigureeachListViewItemintheListView.Althoughthesestyles
arefreetotweakanyproperty,theyusuallydotheirworkbyreplacingthe
ControlTemplatethat’susedfortheListViewandtheDataTemplatethat’susedfor
eachListViewItem.
THE LISTVIEW

CreatingCustomView
Thefollowingexampleshowsyouhowtocreateagridthatcanbeswitched
seamlesslyfromoneviewtoanother.Thegridbeginsinthefamiliarcolumn-
separatedviewbutalsosupportstwotiledimageviews,asshowninFigure22-3
andFigure22-4.
THE LISTVIEW

UsingtheListview
C#Code
XAMLCode
THE LISTVIEW
<ListViewx:Name="lstView" HorizontalAlignment="Left" Height="153" VerticalAlignment="Top" Width="465">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContextMenu >
<ContextMenu/>
</GridView.ColumnHeaderContextMenu >
<GridViewColumnHeader="Firstname" Width="150" DisplayMemberBinding="{Binding Path=fName}"/>
<GridViewColumnHeader="Middlename" Width="150" DisplayMemberBinding="{Binding Path=mName}"/>
<GridViewColumnHeader="Lastname" Width="150" DisplayMemberBinding="{Binding Path=lName}"/>
<GridViewColumnHeader="Extension" Width="50" DisplayMemberBinding="{Binding Path=eName}"/>
</GridView>
</ListView.View>
</ListView>
private void button_Click(object sender, RoutedEventArgse) {
List<Person> items = new List<Person>();
items.Add(new Person() { fName= firstnameTextBox.Text ,
mName= middlenameTextBox.Text ,
lName= lastnameTextBox.Text ,
eName= extensionnameTextBox.Text});
lstView.Items.Add(items); }
public class Person {
public string fName{ get; set; }
public string mName{ get; set; }
public string lName{ get; set; }
public string eName{ get; set; } }

UsingtheListview
THE LISTVIEW

TheTreeViewisaWindowsstaple,andit’sacommoningredient
ineverythingfromtheWindowsExplorerfilebrowsertothe.NET
helplibrary.WPF’simplementationoftheTreeViewisimpressive,
becauseithasfullsupportfordatabinding.
TheTreeViewis,atitsheart,aspecializedItemsControlthathosts
TreeViewItemobjects.ButunliketheListViewItem,theTreeViewItem
isnotacontentcontrol.Instead,eachTreeViewItemisaseparate
ItemsControl,withtheabilitytoholdmoreTreeViewItemobjects.
Thisflexibilityallowsyoutocreateadeeplylayereddatadisplay.
THE TREEVIEW

Here’stheskeletonofaverybasicTreeView,whichisdeclared
entirelyinXAMLmarkup:
THE TREEVIEW

Here’stheskeletonofaverybasicTreeView,whichisdeclared
entirelyinproperties:
THE TREEVIEW

BindingaDataSettoaTreeView
YoucanalsouseaTreeViewtoshowamultilayeredDataSet—onethathas
relationshipslinkingoneDataTabletoanother.
Forexample,here’sacoderoutinethatcreatesaDataSet,fillsitwitha
tableofproductsandaseparatetableofcategories,andlinksthetwotables
togetherwithaDataRelationobject:
THE TREEVIEW

DataGridisadata-displaycontrolthattakestheinformationfroma
collectionofobjectsandrendersitinagridofrowsandcells.Eachrow
correspondstoaseparateobject,andeachcolumncorrespondstoa
propertyinthatobject.
TheDataGridaddsmuch-neededversatilityfordealingwithdatainWPF.Its
column-basedmodelgivesitremarkableformattingflexibility.Itsselection
modelallowsyoutochoosewhetheruserscanselectarow,multiplerows,or
somecombinationofcells.Itseditingsupportispowerfulenoughthatyoucan
usetheDataGridasanall-in-onedataeditorforsimpleandcomplexdata.
THE DATAGRID

Tocreateaquick-and-dirtyDataGrid,youcanuseautomaticcolumn
generation.Todoso,youneedtosettheAutoGenerateColumns propertyto
true(whichisthedefaultvalue):
THE DATAGRID
<DataGridx:Name="gridPerson" AutoGenerateColumns="True">
</DataGrid>

Tocreateaquick-and-dirtyDataGrid,youcanuseautomaticcolumn
generation.Todoso,youneedtosettheAutoGenerateColumns propertyto
true(whichisthedefaultvalue):
XAMLCode
C#Code
THE DATAGRID
private void Window Loaded(object sender, RoutedEventArgse)
{
PersonalInformationDataSetTableAdapters.Person_tabTableAdapter pA;
pA= new PersonalInformationDataSetTableAdapters.Person_tabTableAdapter ();
PersonalInformationDataSet.Person_tabDataTablepT;
pT= new PersonalInformationDataSet.Person_tabDataTable();
pA.Fill(pT);
dtgPersonInfo.DataContext= pT;
}
DataGridName=“dtgPersonInfo" AutoGenerateColumns="True"
ItemsSource="{Binding}" Grid.ColumnSpan="4" Margin="0,45,0,-205" Grid.Row="2"/>

WPFprovidestwomenucontrols:Menu(formainmenus)and
ContextMenu(forpopupmenusthatareattachedtoother
elements).LikealltheWPFclasses,WPFperformstherenderingfor
theMenuandContextMenucontrols.Thatmeansthesecontrols
aren’tsimpleWin32wrappers,andtheyhavetheflexibilitytobe
usedinsomeunusualways.
MENUS

TheMenuClass
WPFdoesn’tmakeanyassumption
aboutwhereastand-alonemenushould
beplaced.Ordinarily,you’lldockitat
thetopofyourwindowusinga
DockPanelorthetoprowofaGrid,and
you’llstretchitacrosstheentirewidthof
yourwindow.However,youcanplacea
menuanywhere,evenalongsideother
controls(asshowninFigure25-1).
Furthermore,youcanaddasmany
menusinawindowasyouwant.
Althoughitmightnotmakemuchsense,
youhavetheabilitytostackmenubars
orscatterthemthroughoutyouruser
interface.
MENUS

MenuItems
MenusarecomposedofMenuItem
objectsandSeparatorobjects.The
MenuItem classderivesfrom
HeaderedItemsControl, because
eachmenuitemhasaheader(which
containsthetextforthatitem)and
canholdacollectionofMenuItem
objects(whichrepresentsasubmenu).
TheSeparatorsimplydisplaysa
horizontallineseparatingmenuitems.
Here’s a straightforward
combinationofMenuItemobjectsthat
createstherudimentarymenu
structureshowninFigure25-3:
MENUS
Setting menu item in
XAML

MenuItems
MENUS
Setting menu item in
Properties

Toolbarsandstatusbarsaretwowell-wornstaplesofthe
Windowsworld.Botharespecializedcontainersthatholda
collectionofitems.Traditionally,atoolbarholdsbuttons,anda
statusbarconsistsprimarilyoftextandothernoninteractive
indicators(likeaprogressbar).However,bothtoolbarsandstatus
barsareusedwithavarietyofdifferentcontrols.
InWindowsForms,toolbarsandstatusbarshavetheirown
contentmodel.Althoughit’sstillpossibletoplacearbitrarycontrols
insideatoolbarandstatusbarusingawrapper,theprocessisn’t
seamless.TheWPFtoolbarandstatusbardon’thavethislimitation.
TheysupporttheWPFcontentmodel,allowingyoutoaddany
elementtoatoolbarorstatusbarandgivingyouunparalleled
flexibility.
TOOLBARS AND STATUS BARS

TheToolbar
AtypicalWPFToolBarisfilledwithButton,ComboBox,CheckBox,RadioButton,and
Separatorobjects.Becausetheseelementsareallcontentcontrols(exceptforthe
Separator),youcanplacetextandimagecontentinside.Althoughyoucanuse
otherelements,suchasLabelandImagetoputnoninteractiveelementsintothe
ToolBar,theeffectisoftenconfusing.
Todemonstratewhatthislookslike,considerthesimplemarkupshownhere:
TOOLBARS AND STATUS BARS
Figure 25-5 shows this toolbar in action, with two CheckBox
controls in the checked state and the drop-down list on
display.

TheToolbar
TodemonstrateinDesignershownhere:
TOOLBARS AND STATUS BARS

TheToolbarTray
TheToolBarTraymakesiteasierfortoolbarstosharethesame
row,orband.YoucanconfiguretheToolBarTraysothattoolbars
shareaband,whileothersareplacedonotherbands.The
ToolBarTrayprovidestheshadedbackgroundbehindtheentire
ToolBararea.Butmostimportant,theToolBarTrayaddssupportfor
toolbardrag-and-dropfunctionality.Unlessyousetthe
ToolBarTray.IsLockedpropertytotrue,theusercanrearrangeyour
toolbarsinaToolBartraybyclickingthegripattheleftside.
Toolbarscanberepositionedinthesamebandormovedtoa
differentband.
TOOLBARS AND STATUS BARS

TheToolbarTray
Here’ssomesamplemarkupthatcreatesseveraltoolbarsinaToolBarTray.
Figure25-7showstheresult
TOOLBARS AND STATUS BARS

TheToolbarTray
Here’ssomesampledesignerthatcreatesseveraltoolbarsinaToolBarTray.Figure25-7
showstheresult
TOOLBARS AND STATUS BARS

TheStatusbar
TheStatusBardoesn’tworkverywellifyouwanttouseoneof
theButtonBase-derivedelementsortheComboBox.Itdoesn’t
overridethestylesofanyofthesecontrols,sotheylookoutof
placeinthestatusbar.Ifyouneedtocreateastatusbarthat
includesthesecontrols,youmightconsiderdockinganordinary
ToolBarcontroltothebottomofyourwindow.It’sprobablyasa
resultofthisgenerallackoffeaturesthattheStatusBarisfoundin
theSystem.Windows.Controls.Primitivesnamespaceratherthanin
themoremainstreamSystem.Windows.Controlsnamespacewhere
theToolBarcontrolexists.
TOOLBARS AND STATUS BARS

TheStatusbar
Onewaytogetproportionallyorright-aligneditemsistouseaGridforyourlayout
container.TheonlytrickisthatyoumustwrapthechildelementinaStatusBarItem
objectinordertosettheGrid.Columnpropertyappropriately.Here’sanexamplethat
usesaGridtoplaceoneTextBlockontheleftsideofaStatusBarandanotheronthe
rightside:
TOOLBARS AND STATUS BARS

TheStatusbar
Settingindesigner.
TOOLBARS AND STATUS BARS

Withtheribbon,Microsoftfounditselffacedwithafamiliardilemma.To
improvetheproductivityandconsistencyofallWindowsapplications,
Microsoftwantedtoencourageeveryapplicationtoadopttheribbon.But
becauseMicrosoftalsowantedtokeepitscompetitiveedge,itwasn’tina
rushtoreleasetheAPIsthatwouldmakethatpossible.Afterall,Microsoftspent
thousandsofhoursofresearchanddevelopmentinperfectingitsversionof
theribbon,soit’snosurprisethatthecompanytookafewyearstoenjoythe
result.
Fortunately,thewaithasended,andMicrosofthasnowmadeaversionof
theribbonavailabletoWPFdevelopers.Thegoodnewsisthatit’scompletely
freeandrespectablyfull-featured,includingrichtooltips,drop-downbuttons,
dialoglaunchers,aquickaccesstoolbar,andconfigurableresizing.
RIBBONS

Theribboncontrolisn’tincludedwiththe.NETFramework.Instead,it’s
availableasaseparatedownload,whichisconsideredtobea“preview”
versionatthetimeofthiswriting.YoucandownloaditfromtheOfficeUI
Licensingwebsiteathttp://msdn.microsoft.com/officeui(lookfora“License
theOfficeUI”link).Don’tbeintimidatedabouttheterminology—licensing
simplymeansprovidingyourcontactinformationandacceptingaone-page
agreementthatstatesthatyouwillfollowtheOfficeUIdesignguidelines.(In
otherwords,Microsoftdoesn’twantyouusingtheribboncontrolifyouaren’t
usingitright.)Youcanfindribbonguidelinesandbestpracticesat
http://tinyurl.com/4dsbef.
Onceyou’vedownloadedtheribbon,you’llgetasinglecompiledclass
libraryassembly,namedRibbonControlsLibrary.dll.Tostartusingtheribbon,
addareferencetothislibraryinanyWPFapplication,andkeepreading.
RIBBONS

AddingtheRibbon
Aswithanycontrolthat’snotapartofthecoreWPFlibraries,youneedto
mapthecontrolassemblytoanXMLprefixbeforeyoucanuseit:
<Windowx:Class="RibbonTest.MainWindow"...xmlns:r=
"clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary">
YoucanthenaddaninstanceoftheRibboncontrolanywhereinyour
window:
<r:Ribbon>
</r:Ribbon>
RIBBONS

AddingtheRibbon
TheRibbonControlsLibrary.dllassemblyaddressesthisissuebyincludingthe
RibbonWindow—aclassthatderivesfromWindowandintegratesmore
seamlesslywiththeribbon.Figure25-8comparesthedifference.
RIBBONS

AddingtheRibbon
Here’sabasicskeletonforacustomwindowthatderivesfrom
RibbonWindowandplacestheribbonatthetop,whilereservingthesecond
rowofaGridfortheactualwindowcontent.
RIBBONS

SylingtheRibbon
There’sonemoredetailtoconsiderbefore
youstartfillingtheribbonwithbuttons.
Ordinarily,theribbonisstyledtolooklikethe
ribboninWindows7applications(likePaint).
Thatmeanstheapplicationmenubuttonisa
squarethatsitsjustunderthewindowborder
andquickaccesstoolbar,andthebackground
oftheribbonblendsintothebackgroundofthe
windowframe.YourotherchoiceistouseOffice
2007styling,whichappliesamoredramatic
backgroundcolor,turnstheapplicationmenu
buttonintoalargecircle,andmovesituptothe
top-leftcornerofthewindow.Figure25-9shows
thedifference.
RIBBONS

Commands
Theribbonisbuiltaroundtheconceptofcommands.Thesecommands
powerallpartsoftheribbon,includingitsbuttons,theapplicationmenu,and
thequickaccesstoolbar.
UnlikeWPF’sstandardmenuandtoolbars,theribbondoesn’tallowyouto
interceptClickeventsfromitsconstituentcontrols.Instead,itforcesyoutouse
ahigher-leveldesignandtowiretheribboncontrolstocustomcommand
objects.
Tosupportthissystem,theribbonincludesanewclassthatderivesfrom
RoutedCommand ,calledRibbonCommand .Theadvantageofthisdesignis
thatitallowstheribbontosupplyrichercommand functionality.(Asyou
learnedinChapter9,WPF’sbasiccommand modelisprettymodest.)The
disadvantageofthisdesignisthatitmeansyoucan’tuseanycustomclasses
youmayhavealreadyderivedfromRoutedCommand withtheribbon.
RIBBONS

Commands
Table25-1liststhe
properties that the
RibbonCommand addsto
thebaseRoutedCommand .
RIBBONS

TheApplpicationMenu
Theeasiestwaytogetstartedwiththeribbonistofilltheapplicationmenu.
Theapplicationmenuisbasedontwostraightforwardclasses:
RibbonApplicationMenu(whichderivesfromMenuBase)andRibbonMenuItem
(whichderivesfromMenuItem).Thisestablishesapatternyou’llseethroughout
thissection—theribbontakesthebaseWPFcontrolclassandderivesmore
specializedversions.Fromapuristpointofview,thisisn’tideal.TheToolBarand
StatusBarhaveafarcleanermodel,becausethey’reabletoworkwith
standardWPFcontrols,whichtheysimplyrestyle.
RIBBONS

TheApplpicationMenu
Tocreateamenu,youcreateanewRibbonApplicationMenuobjectand
usethattosettheRibbon.ApplicationMenuproperty.Asyouprobablyalready
expect,theRibbonApplicationMenu includesacollectionof
RibbonApplicationMenuItem objects,eachofwhichrepresentsaseparate
clickablemenuitem.
Here’sabasicexampleoutlinethatcreatesanapplicationmenuwiththree
menuitems:
RIBBONS

TheApplpicationMenu
Toconfigureeachcommand, you
simply need to supply a
RibbonCommand object.Thisobject
specifiesthemenutext(throughthe
LabelTitleproperty),anoptionaltooltip
(using the ToolTipTitle,
ToolTipDescription,andsoon),an
optionalimage(LargeImageSource),
andtheeventhandlerthatshouldbe
triggeredwhenthemenuitemisclicked
(Executed).AsyoulearnedinChapter
9,youcanalsohandletheCanExecute
eventtoconfigurewhether a
command shouldbeenabledor
disabled.
Here’sanexamplethatfillsinthe
threecommands (butleavesoutthe
optionaltooltipproperties):
RIBBONS

TheApplpicationMenu
The top-levelRibbonApplicationMenu
objectalsoneedsaRibbonCommand object,
eventhoughitisn’tusedtotriggeracommand!
That’sbecauseafewoftheotherproperties,
suchasthetooltippropertiesandtheimage
properties(whichsettheimagethatappearsin
theapplicationmenubutton).Ifyou’reusing
thedefaultWindows7style,youneedtosetthe
SmallImageproperty,whiletheOffice2007
styleshavealargeapplicationbuttonand
needtohavetheLargeImageSourceproperty.
It’salsoworthnotingthatany
RibbonApplicationMenuItem canholdmore
RibbonApplicationMenuItemobjectstocreate
asubmenu.Thesubmenuisdisplayedinthe
secondcolumnofthemenu,asshowninFigure
25-10.
RIBBONS

TheApplpicationMenu
Whencreatingasubmenu,youcansettheRibbonCommand .LabelTitleproperty
ofthecontainingRibbonApplicationMenuItemobjecttoaddatitlethatwillbeshown
overthesubmenu,asinFigure25-10.Here’sthemarkupyouneed:
RIBBONS

Tabs,GroupsandButtons
Theribbonusesthesamemodeltofillits
toolbartabsasitdoestofillitsapplication
menu,justwithafewextralayers.
First,theribbonholdsacollectionoftabs.
Inturn,eachtabholdsoneormoregroups,
whichisanoutlined,titled,boxlikesectionof
theribbon.Lastly,eachgroupholdsoneor
moreribboncontrols.Figure25-11showsthis
arrangement.
RIBBONS

RibbonSizing
Oneoftheribbon’smostremarkable
featuresisitsabilitytoresizeitselftofitthe
widthofthewindowbyreducingand
rearrangingthebuttonsineachgroups.
Figure25-12illustratesthisprocesswitha
ribbonthathasthreecopiesoftheFilegroup.
Thefirstisfullyexpanded,thesecondis
partiallycollapsed,andthesecondis
completelycollapsed.(It’sworthnotingthatin
ordertocreatethisexample,theribbonmust
beexplicitlyconfiguredtonotcollapsethe
firstgroup.Otherwise,itwillalwaystryto
partiallycollapseeverygroupbeforeitfully
collapsesanygroup.)
RIBBONS

RibbonSizing
Totakecontrolofgroupresizing,you
need to define multiple
RibbonGroupSizeDefinitionobjectsand
orderthemfromlargesttosmallestina
RibbonGroupSizeDefinitionCollection.Asthe
groupiscollapsed,theribboncanthen
switchfromonelayouttothenexttoreclaim
morespace,whilekeepingthelayoutyou
want(andensuringthatthecontrolsyou
thinkaremostimportantremainvisible).
Usually, you’ll place the
RibbonGroupSizeDefinitionCollectioninthe
Ribbon.Resourcessection,soyoucanreuse
thesamesequencesoftemplatesformore
thanonefour-buttongroup
RIBBONS

TheQuickAccessToolbar
Thefinalingredientthatyou’llconsiderintheribbonisthequick
accesstoolbar(orQAT).It’sanarrowstripofcommonlyused
buttonsthatsitseitherjustaboveorjustbelowtherestofthe
ribbon,dependingonuserselection.
TheQATisrepresentedbytheQuickAccessToolBarobject,which
holdsaseriesofRibbonButtonobjects.Whendefiningthe
RibbonCommand fortheseobjects,youneedonlysupplythe
tooltiptextandsmallimage,becausetextlabelsandlargeimages
arenevershown.
RIBBONS

TheQuickAccessToolbar
TheonlynewdetailintheQATisthecustomizemenuthatappears
whenyouclickthedrop-downarrowoffthefarrightofit(Figure25-13).You
canusethismenutoletuserscustomizethecommandsthatappearinthe
QAT.Or,youcandisablethecustomizemenu bysetting
QuickAccessToolBar.CanUserCustomizetofalse.
RIBBONS
Tags