How can I control the layout of items in WPF?
WPF attempts to bring the best of rich-client technologies like Windows Forms, and layout techniques from the browser to give a high degree of flexibility when positioning elements on forms.
Rich client technologies like VB6 forms, Access Forms etc were based on absolute positioning. As a developer you specified the top and left values for a control to position it on the form. This allows for a fine degree of control, but often required a large amout of code to handle form re-sizing. This was an imperative approach to layout. Controls like Labels and Panels had no awareness of the size of the content inside them - for example if the content of a label was larger than what could be displayed in the label then the content is clipped, and not shown.
Web UI rendered in the browser typically require no re-sizing code. Instead HTML gives a declarative approach to the layout of elements. You specify a serise of containers like <div> elements (or <table>, <tr> and <td> elements if you haven't become convinced of the benefits of positional CSS-based layouts) and position those by either floating them Left or Right, or positioning them absolutely in your page. Elements like <div> are aware of the size of their contents and will stretch to accomodate their content.
Both these approaches could be equally difficult to achieve the desired layout, although the declarative approach had the advantage of requiring much less code to do so. Recently windows forms has added concepts like Docking and Anchoring, adding a more declarative approach to rich-client development. WPF continues this trend with a declarative approach to layout based on the concept of panels.
Most UI elements in WPF can only contain a single child element - for example the following Xaml code fails to compile with the following error: "The 'Button' object already has a child and cannot add 'CheckBox'. 'Button' can accept only one child."
Xaml Syntax (does not compile)
<Button>
<TextBlock>Some Text...</TextBlock>
<CheckBox />
<ComboBox />
</Button>
If the button allowed these two elements to be nested inside it it would be responsible for laying them out somehow. Since there are many possible ways these items could be layed out the button would have to become a much more complicated control to accomodate them all, and would now have two "responsibilities" - allowing the user to click on it, and laying out content. Not only would the button become much more complicated but all the controls in WPF would become more complicated. Instead of taking this approach the WPF team decided to factor out the responsibility for layout to a different control - the panels. There are a number of different types of panels in WPF and each enables a different kind of layout. Panels can be nested wherever regular content can be placed, allowing a fine degree of control over the layout of items. For example to correct the problem in the example above we could nest a StackPanel inside the button, and position the elements inside the StackPanel
<Button>
<StackPanel>
<TextBlock>Some Text...</TextBlock>
<CheckBox />
<ComboBox />
</StackPanel>
</Button>
This give the following layout:
Having briefly introduced the important role panels play in controlling layout in WPF let's look at the most commonly used panel types and their characteristics.
StackPanel
The StackPanel lays out child elements by stacking them one after the other. Elements are "stacked" in the order they appear in the Xaml file (document order in XML terms). Items can either be stacked vertically (the default) or horizontally.
Xaml Syntax for Stacking Vertically (Feb 2006 CTP):
<StackPanel>
<TextBlock FontSize="16"
Foreground="#58290A">
Items inside a StackPanel</TextBlock>
<Button>Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2">
<TextBlock>Item 3</TextBlock>
</Border>
</StackPanel>
Xaml Syntax for Stacking Horizontally (Feb 2006 CTP):
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="16"
Foreground="#58290A">
Items inside a StackPanel</TextBlock>
<Button>Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2">
<TextBlock>Item 3</TextBlock>
</Border>
</StackPanel>
WrapPanel
The wrap panel lays out items from left to right. When a row of items has filled the horizontal space available to them the panel wraps the next item around onto the next line (in a similar way to how text is layed out).
Xaml Syntax (Feb 2006 CTP):
<WrapPanel>
<TextBlock FontSize="16"
Foreground="#58290A">
Items inside a WrapPanel</TextBlock>
<Button>Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2">
<TextBlock>Item 3</TextBlock>
</Border>
</WrapPanel>
DockPanel
The DockPanel allows elements to be docked to the edges of the panel's container, similar to Windows Forms docking. Items are docked in the order they appear in the Xaml file (document order). The last Border element fills all the remaining space since no DockPanel.Dock attribute is specified for it.
Xaml Syntax (Feb 2006 CTP):
<DockPanel>
<TextBlock FontSize="16" DockPanel.Dock="Top"
Foreground="#58290A">
Items inside a DockPanel</TextBlock>
<Button DockPanel.Dock="Left">Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2">
<TextBlock>Item 3</TextBlock>
</Border>
</DockPanel>
Canvas
The Canvas panel is similar to the way old rich-client layout worked where you control the absolute position of things by setting a Top and Left property for them. Additionally, instead of setting the Left to position an item you can instead set the Right, or instead of setting the Top you can set the Bottom. If you specify a Left and a Right the Right value is ignored, the element does not change its size to make both these values correct, and similarly Top takes precedence over Bottom. Elements that are declared earlier in the Xaml file can appear behind elements that are declared later (if their positions over-lap).
Xaml Syntax (Feb 2006 CTP):
<Canvas>
<TextBlock FontSize="16" Canvas.Top="10" Canvas.Left="20"
Foreground="#58290A">
Items inside a Canvas</TextBlock>
<Button Canvas.Bottom="25" Canvas.Right="50">Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2"
Canvas.Top="20" Canvas.Left="50">
<TextBlock>Item 3</TextBlock>
</Border>
</Canvas>
Grid
The Grid panel is an extremely flexible panel, and can be used to achieve almost everything that can be done with the other panel controls (although often not with the same ease). The grid panel allows you to define rows and columns in the grid using Xaml, and then place controls in calls in the grid using grid-specific attributes. Elements can span multiple rows or columns. The grid will automatically make all its rows and columns the same size (based on the size of the content) but you can specify a proportional size for rows and columns using a star notation, or specify an absolute width or height. The star notation can be seen in the example code below where one of the columns is twice the width of the other column by setting the Width attribute to "2*". The example below also shows the height of one row being set to an absolute value. The differences these introduce can more readily be seen when re-sizing the form containing the grid, as the grid will expand by default to fill the space available to it. The example below also has the ShowGridLines attribute of the grid set to True to help you visualize the space each row and column is taking up. A broader range of layout tricks for the grid panel is beyond the scope of this introduction, but hopefully we'll be able to re-visit this soon in a future article.
Xaml Syntax (Feb 2006 CTP):
<Grid Margin="10" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition />
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<TextBlock FontSize="16"
Foreground="#58290A"
Grid.Column="0" Grid.Row="0"
Grid.ColumnSpan="2"
>
Items inside a Grid</TextBlock>
<Button Grid.Column="0" Grid.Row="1">
Item 2</Button>
<Border BorderBrush="#feca00" BorderThickness="2"
Grid.Column="1" Grid.Row="2">
<TextBlock>Item 3</TextBlock>
</Border>
</Grid>
We can see from the different examples above that the different Panel controls not only influence the position of the elements they're laying out, but also their size.
Implementing a Custom Panel
The WPF layout system is not limited to the layouts that are included by default. If you need a special layout that can't easily be achieved with the built-in panels you can implement your own. WPF Program Manager Kevin Moore has implemented two custom panels - an animating tile panel and a TreeMapPanel . The source for these built with the February CTP (the most recent at the time of writing) is available here.
Categories:
Comments:
#
Your Article
posted by
Shakeel
on
11/9/2007 4:25:32 AM
:
This is certainly a very useful tutorial, keep up the good work.
#
Great Tutorial!
posted by
Yaniv Hakim
on
3/18/2008 8:55:22 PM
:
at last simple explanation...
#
Simple and Thorough
posted by
Hanch
on
4/2/2008 5:17:18 PM
:
Great. 2 min. tutorial equals to a one month MS training
#
Wish everybody could make learning so simple
posted by
Neetika
on
6/11/2008 1:41:42 PM
:
Wish everybody could make learning so simple
#
How can I control the layout of items in WPF?
posted by
Mike
on
9/25/2008 3:07:58 AM
:
Thank you... thank you so very much...
#
You Cleared Lot !
posted by
Mathivanan
on
11/27/2008 11:27:22 PM
:
You cleared lot of confusion and Saved my time.. Keep posting ):
#
Nice Article
posted by
Sathish
on
1/15/2009 5:57:25 PM
:
It is extremely helpful article for begineers' like me...
#
oh wow thanks
posted by
angry wpf guy
on
3/20/2009 10:38:16 PM
:
:D
#
Great Article
posted by
Vipul
on
4/2/2009 8:56:05 PM
:
Fantastic article...
Very simple and very clear
#
Good Writeup
posted by
Kamal
on
5/5/2009 3:28:34 PM
:
simple and explanatory..
#
professional shoes
posted by
nike shox shoes
on
11/12/2009 10:39:52 PM
:
Flat feet is a mbt shoes growing problem. A lot of professional shoes people are getting pronation in the mbt usa ankle which relates to knee pain mbt uk which relates to knee injury, which relates to the hip to the back. It all nike shox shoes relates to everything, it all starts at your feet.a sports mbt outlet and prada shoes recreation manager and former Australian Olympic volleyballer, also recommends people spend money on mbt footwear to reduce the risk of injury.
http://www.airjordanshow.com/
#
Ugg Boots,
posted by
Ugg Boots
on
11/13/2009 11:41:01 PM
:
It is no use doing what ugg bailey button you like ugg boots ; you have got to like ugg classic cardy what you do My philosophy of ugg lo pro button life is work . When work is a pleasure , life is joy ! When work is duty ,ugg knightsbridge life is slavery .Work banishes those three great evils : boredom , vice, and poverty.
http://www.uggshow.co.uk/specials.html
#
http://www.ladyugs.com/specials.html
posted by
Ugg Classic Boots
on
11/26/2009 1:56:58 PM
:
S11125H2 Towering genius disdains a beaten path with discount ugg boots. It seeks regions hitherto unexplored.A man may lead a horse to the water, but he cannot make it drink and walk with ugg classic tall .Victory wil not come to ugg lo pro button unless I go to ugg classic cardy.Goals determine what you are going to ,for example, buy ugg knightsbridge.
http://www.ladyugs.com/specials.html
#
timberland custom boots
posted by
timberland chukka boots
on
12/4/2009 12:23:41 PM
:
S11204I2
The son of wealthy and influential Athenian parents, Plato began his timberland chukka boots philosophical career as a student of Socrates. When the master died, Plato travelled timberland waterproof boots to Egypt and Italy, studied with students of Pythagoras, and spent timberland work boots several years advising the ruling family of Syracuse. Eventually, he returned timberland custom boots to Athens and established his own school of philosophy at the Academy.For students enrolled there, Plato tried timberland high top boots both to pass on the heritage of a Socratic style of thinking Timberland Men's Roll-Top and to guide their progress through mathematical learning to the achievement of abstract philosophical truth.
http://www.officialtimberland.com/products_new.html
#
timberland high top boots
posted by
timberland chukka boots
on
12/5/2009 3:56:16 PM
:
S11205I2
The son of wealthy and influential Athenian parents, Plato began his timberland chukka boots philosophical career as a student of Socrates. When the master died, Plato travelled timberland waterproof boots to Egypt and Italy, studied with students of Pythagoras, and spent timberland work boots several years advising the ruling family of Syracuse. Eventually, he returned timberland custom boots to Athens and established his own school of philosophy at the Academy.For students enrolled there, Plato tried timberland high top boots both to pass on the heritage of a Socratic style of thinking and to guide their progress through mathematical learning to the achievement of abstract philosophical truth.
http://www.officalsale.com/specials.html
#
Cardy Ugg Boots
posted by
Cardy Ugg Boots
on
1/8/2010 4:29:01 PM
:
slLAH100108 I think this blog is good,so now I wanna introduce mbt to you.{{[MBT Chapa shoes->
http://www.cutembt.com/mbt-chapa-shoes-c-71.html]}} are a growing and popular anti-shoe inspired by the Masai people. The Masai people are known for their athletic posture and gait. It is known that none of the Masai people struggle with any back pain due to walking on hard surfaces,so they try {{[MBT Women M.Walk shoes->
http://www.cutembt.com/mbt-women-mwalk-shoes-c-42.html]}}. At last,they found the benefit of MBT Women M.Walk shoes, they trust mbt shoes.
#
mbt shoes,cheap mbt shoes,mbt shoes sale,mbt sale, mbt review
posted by
mbt walking shoes
on
1/12/2010 2:22:49 AM
:
100109SLZLP We should so live and labor in our mbt walking shoes time that mbt usa what came to us as seed may go to the next mbt sandals generation as blossom,and what mbt sneakers came to us as blossom may go to them as fruit. This is what mbt footwear clearance we mean by progress. It is better to die on your feet than to live on your knees.
http://www.mbttoday.com/
#
uggs on sale
posted by
ugg boots
on
1/26/2010 11:34:56 AM
:
100126SLLYH
Our greatest glory uggs boots consists not in never falling but in rising every ugg classic tall time we fall.It is not enough ugg classic boots to be industrious, so are the ants. What are you industrious about ugg classic argyle knit? You have to believe in yourself. That's the ugg bailey button secret of sucess. A wise man never loses anything if he has himself. To be without some of the things you want is an indispensable part of happiness.
http://www.4ezlive.com/
#
replica gucci
posted by
replica gucci
on
3/22/2010 4:34:38 PM
:
His two children, ages 4 and 7, were wounded and transported to a hospital, the attorney general's office replica hermes said. Salcido's wife was traveling in another vehicle, which was not attacked, Reyes hublot replica said. In Washington, President Obama and Secretary of State Hillary Clinton replica hublot watch anger. The president is deeply saddened and outraged by the news of replica hublot watches the brutal murders of three people associated with the United States Consulate General in Ciudad replica hublot Juarez, National Security Council spokesman Mike Hammer.
http://www.overwatches.com/alain_silberstein-watches.htmlhttp://www.overwatches.com/armani-watches.html
#
jaeger lecoultre
posted by
jaeger lecoultre
on
3/24/2010 4:07:55 PM
:
In the other theater, The Pacific replica jaeger lecoultre watches makes painfully clear in its early episodes, the Marines that it follows had no idea what they were getting into. On the one hand jaeger lecoultre replica, the replica jaeger lecoultre watches war was simple: Japan attacked the U.S. at Pearl Harbor, and now we were going to get those bastards back. On the other hand, they were going to be introduced to a kind of war they had scarcely imagined, on replica jaeger lecoultre watch islands they didn't know, at a replica jaeger lecoultre watches cost they could not conceive.
http://www.overwatches.com/jaeger_lecoultre-watches.html
#
cartier cpcp
posted by
cartier cpcp
on
3/24/2010 7:43:27 PM
:
But there was, and showing that side is the project of baignoire watches The Pacific, the ten-episode bookend that in nearly every way improves on baignoire its 2001 European-theater predecessor. The war against Japan was different from the war against Hitler militarily, topographically and psychologically. WWII in Europe was, for all its mechanized death and horror, in some ways a throwback: it cartier baignoire was the last great cpcp watches so far land war in Europe, fought in places with replica watches recognizable names by great massed armies.
http://www.wholewatches.com/cartier-baignoire-watches.htmlhttp://www.wholewatches.com/cartier-cpcp-watches.html
#
replica lv
posted by
replica lv
on
3/26/2010 1:19:50 PM
:
Pronto, an environmental studies major who replica lv watch works each summer as a forest firefighter, agreed. Apart from remembering to lower the toilet seat, he said, living with a woman lv replica friend is not much different from rooming with a man. As far replica lv watch as I'm concerned, a roommate is a roommate, he said. Although the number of participants remains small, gender-neutral housing has gained replica lv watch attention as the final step replica lv watch in the integration of student housing.
http://www.overwatches.com/lv-watches.html
#
replica miscellaneous
posted by
replica miscellaneous
on
3/27/2010 2:38:40 PM
:
Pitzer, which has about a dozen students participating this year, avoids such limits out of concern that they may marginalize students, said Chris Brunelle, director of residence miscellaneous replica life. Pitzer miscellaneous replica housing applications ask miscellaneous replica whether students prefer a roommate to be woman, man, other, or have no preference. Or students replica miscellaneous can request to live together, as Eland and Pronto did replica miscellaneous watch after losing replica miscellaneous their original roommates.
http://www.overwatches.com/miscellaneous-watches.html
#
Mbt shoes
posted by
Mbt shoes
on
3/29/2010 1:25:47 PM
:
MBT Shoes Sale offer powerful training shoes Cheap MBT Shoes.
Mbt shoes made from high quality Nappa leather are strong and enduring.mbt shoes Best Prices available at cheap mbt shoes help to build body
#
replica watches
posted by
replica watches
on
4/5/2010 10:48:50 AM
:
But what about regular moviegoers would they even notice replica watches anything amiss with the movie’s 3-D? It’s no small question for replica watches Hollywood. With at least 70 movies replica watches in the 3-D pipeline including many similar replica watches conversion projects studios and theater owners are betting replica watches heavily that audiences will snap up increasingly expensive replica watches 3-D tickets.
http://www.watchvisa.com
#
replica watches
posted by
replica watches
on
4/5/2010 12:18:10 PM
:
I thought the 3-D quality was really good, said Eric Shimp as replica watches he left a showing of Clash of the Titans at the AMC Century City 15 in Los replica watches Angeles. Mr. Shimp, who works in the automotive industry, added replica watches, The ticket prices are ridiculous, but it does leave replica watches you feeling like you’ve just seen a spectacle. Sharle Kochman, a cosmetologist, said replica watches as she left the theater that she thought the 3-D quality was on a par with Avatar.
http://www.overwatches.com
#
Links of London Jewellery
posted by
Links of London Jewellery
on
4/8/2010 2:11:59 PM
:
Their eyes and ears take in all sights and sounds hazily, without concentration and with little appreciation. It is the same old story of not being grateful for what we have until we lose it, of not being conscious of health until we are ill.
#
replica rolex watches
posted by
replica rolex watches
on
4/10/2010 3:48:22 PM
:
For the most part, I have done a pretty good job. I once told a replica watches local pharmacist who charged rolex watch me twice to send the same fax that if he didn't give me my money back, I would never come into rolex watch his store again. He thought it was an idle threat. Twenty years later, I was still rolex watches snubbing him, right up until the day he went to prison for Medicaid fraud.
http://www.watchessell.com/product.php?id=4&categories_id=36
#
Replica BRM Watches
posted by
Replica BRM Watches
on
4/15/2010 1:26:14 PM
:
I am willing to give you a big surprise: <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com title=replica brand watches>replica-brand-watches.com</a> is <a href=
http://www.offerreplicawatches.com title=offer replica watches>offer replica watches</a>. I bought an <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-iwc-watches_g1179 title=replica IWC Watches>replica IWC Watches</a> a week ago from this site. They sell a wide range of <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com title=replica watches>replica watches</a>, such as <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-chanel-watches_g1138 title=Replica Chanel Watches>Replica Chanel Watches</a>, <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-brm-watches_g1172 title=replica B.R.M Watches>replica B.R.M Watches</a> on sale, <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-rolex-watches_g1190 title=replica Rolex watches>replica Rolex watches</a> for sale, <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-omega-watches_g1184 title=replica Omega watches>replica Omega watches</a>, buy <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-christian-dior-watches_g1769 title=replica Christian Dior watches>replica Christian Dior watches</a>, sell <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-gucci-watches_g1682 title=replica Gucci watches>replica Gucci watches</a>, <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-cartier-watches_g1174 title=replica Cartier Watches>replica Cartier Watches</a>, <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-richard-mille-watches_g1189 title=replica Richard Mille Watches>replica Richard Mille Watches</a>, Wholesale <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com/Replica-ebel-watches_g1176 title=Replica Ebel Watches>Replica Ebel Watches</a> and so on. And I also hear that they also <a href=
http://www.lovedvddisk.com">
http://www.lovedvddisk.com title=sell DVD Sets>sell DVD Sets</a> which are mainly new and existing. Now, many companies are promoting their products. The more important, their price is very reasonable. If you want to buy the watches and <a href=
http://www.lovedvddisk.com">
http://www.lovedvddisk.com title=DVD Sets>DVD Sets</a> now, it is not a bad choice for you to buy from <a href=
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com">
http://www.replica-brand-watches.com title=replica brand watches>replica-brand-watches.com</a> and <a href=
http://www.lovedvddisk.com">
http://www.lovedvddisk.com/ title=dvd box set>lovedvddisk.com</a> on 99172381231231128
#
rolex watches
posted by
rolex watches
on
4/26/2010 12:21:21 PM
:
That’s all I was asking for. Nothing more, nothing less. Celtics coach replica rolex watches Doc Rivers didn’t see a replay of the incident until yesterday morning, and he thought Richardson was out of line for standing over Pierce as he lay prone. He had no business over replica rolex there, Rivers said. We had replica watches a guy on the floor injured. There was no reason for him to be there. And then, going by all reports, not only just the crowding, but it was the taunting.
http://www.watchesmine.com/rolex-watches.html
#
gdfgfb
posted by
iphone Transfer
on
5/5/2010 6:57:41 PM
:
xbvdfg can mange files as a hard disk, and transfer various files between
iPhone and computer, iPhone and iTunes, iPhone and iPhone, etc. Besides that, iPhone Transfer free can also allows users to rip
DVDs to iPhone in a powerful and easy way.