4
17/12/2014 WPF Tutorial | Introduction to WPF Layout http://www.wpftutorial.net/LayoutProperties.html 1/4 Home Layout Introduction to WPF Layout Share... Feed About Christian Moser Home WPF Inspector Getting started Introduction to WPF Development Tools Books Create a simple WPF application Instruction Videos Learn WPF in two Weeks Fundamentals What's new in XAML in .NET 4.0 XAML Dependency Properties Routed Events Logical‐ and Visual Tree Hard‐ and Softwarerequirements WPF Troubleshooting User Experience UX Design Process Patterns Dependency Injection Undo/Redo Model‐ View‐ ViewModel Pattern DelegateCommand Controls List of 3rd‐ Party Controls ItemsControl LivePreview ComboBox Calendar ToolTips TextBox DataGrid ContextMenu Expander Menus PasswordBox Dialogs Introduction to WPF Layout Why layout is so important Best Practices Vertical and Horizontal Alignment Margin and Padding Width and Height Content Overflow Handling Why layout is so important Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built‐in layout panels that help you to avoid the common pitfalls. These are the five most popular layout panels of WPF: Grid Panel Stack Panel Dock Panel Wrap Panel Canvas Panel Best Practices Avoid fixed positions ‐ use the Alignment properties in combination with Margin to position elements in a panel Avoid fixed sizes ‐ set the Width and Height of elements to Auto whenever possible. Don't abuse the canvas panel to layout elements. Use it only for vector graphics. Use a StackPanel to layout buttons of a dialog Use a GridPanel to layout a static data entry form. Create a Auto sized column for the labels and a Star sized column for the TextBoxes. Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists. Use the SharedSize feature to synchronize the label widths. Vertical and Horizontal Alignment Use the VerticalAlignment and HorizontalAlignmant properties to dock the controls to one or multiple sides of the panel. The following illustrations show how the sizing behaves with the different combinations. Margin and Padding DataGrid control for WPF Fastest, most mature WPF datagrid control. Try the noinstall demo!

WPF Tutorial _ Introduction to WPF Layout

Embed Size (px)

Citation preview

Page 1: WPF Tutorial _ Introduction to WPF Layout

17/12/2014 WPF Tutorial | Introduction to WPF Layout

http://www.wpftutorial.net/LayoutProperties.html 1/4

Home Layout Introduction to WPF Layout Share... Feed About Christian Moser

HomeWPF Inspector

Gettingstarted

Introductionto WPFDevelopmentToolsBooksCreate asimple WPFapplicationInstructionVideosLearn WPFin twoWeeks

FundamentalsWhat's newin XAML in.NET 4.0XAMLDependencyPropertiesRoutedEventsLogical‐and VisualTreeHard‐ andSoftwarerequirementsWPFTroubleshooting

UserExperience

UX DesignProcess

PatternsDependencyInjectionUndo/RedoModel‐View‐ViewModelPatternDelegateCommand

ControlsList of 3rd‐PartyControlsItemsControlLivePreviewComboBoxCalendarToolTipsTextBoxDataGridContextMenuExpanderMenusPasswordBoxDialogs

Introduction to WPF Layout

Why layout is so important

Best Practices

Vertical and Horizontal Alignment

Margin and Padding

Width and Height

Content Overflow Handling

Why layout is so important

Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work foran limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail.WPF provides a rich set built‐in layout panels that help you to avoid the common pitfalls.

These are the five most popular layout panels of WPF:

Grid PanelStack PanelDock PanelWrap PanelCanvas Panel

Best Practices

Avoid fixed positions ‐ use the Alignment properties in combination with Margin to position elements in a panelAvoid fixed sizes ‐ set the Width and Height of elements to Auto whenever possible.Don't abuse the canvas panel to layout elements. Use it only for vector graphics.Use a StackPanel to layout buttons of a dialogUse a GridPanel to layout a static data entry form. Create a Auto sized column for the labels and a Star sized columnfor the TextBoxes.Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists. Use the SharedSize featureto synchronize the label widths.

Vertical and Horizontal Alignment

Use the VerticalAlignment and HorizontalAlignmant properties to dock the controls to one or multiple sides of thepanel. The following illustrations show how the sizing behaves with the different combinations.

Margin and Padding

DataGrid control for WPFFastest, most mature WPF datagrid control. Try the no­installdemo!

rmc
Comentário do texto
Evitar posições fixas - usar as propriedades dos alinhamentos em combinação com as margens para posicionar elementos num painel.
rmc
Nota
Marked definida por rmc
rmc
Realce
Evitar tamanhos fixos - definir a largura e altura dos elementos para auto sempre que possível.
rmc
Realce
Não abusar de painel para elementos de layout. Use apenas para gráficos vetoriais.
rmc
Realce
Use um StackPanel para o layout de botões de uma caixa de diálogo
rmc
Realce
Use um GridPanel para o layout de um formulário de entrada de dados estáticos. Criar uma coluna de tamanho Auto para os rótulos e uma coluna de tamanho Star para os TextBoxes.
rmc
Realce
Use um ItemControl com um painel de grade em um DataTemplate para o layout de listas de valores-chave dinâmicas. Use o recurso de SharedSize para sincronizar as larguras de etiqueta.
Page 2: WPF Tutorial _ Introduction to WPF Layout

17/12/2014 WPF Tutorial | Introduction to WPF Layout

http://www.wpftutorial.net/LayoutProperties.html 2/4

RadioButtonSliderPopup

ListBoxLayoutofItemsApplyaDataTemplateStrechanItemSelectedItemBackground

ListViewTextBlock

WindowRemovetheIcon

CustomControls

UserControlsvs.CustomControlsHow toCreate aCustomControl

Layout

InputKeyboardMouseMutli TouchRoutedCommandsin aContextMenu

Data BindingDataBindingOverview

DataValidation

Set aValidationErrorbyCode

Elegant wayforINotifyPropertyChangedValueConvertersDebugDataBindingIssuesHow toBindEnumValuesDataViewing,Sorting andFilteringPopularDataBindingExpressions

StylingDesigntime

The Margin and Padding properties can be used to reserve some space around of within the control.

The Margin is the extra space around the control.The Padding is extra space inside the control.The Padding of an outer control is the Margin of an inner control.

Height and Width

Alltough its not a recommended way, all controls provide a Height and Width property to give an element a fixed size. Abetter way is to use the MinHeight, MaxHeight, MinWidth and MaxWidth properties to define a acceptable range.If you set the width or height to Auto the control sizes itself to the size of the content.

Overflow Handling

Clipping

Layout panels typically clip those parts of child elements that overlap the border of the panel. This behavior can becontrolled by setting the ClipToBounds property to true or false.

Scrolling

When the content is too big to fit the available size, you can wrap it into a ScrollViewer. The ScrollViewer uses two scrollbars to choose the visible area.

The visibility of the scrollbars can be controlled by the vertical and horizontal ScrollbarVisibility properties.

<ScrollViewer>    <StackPanel>        <Button Content="First Item" />        <Button Content="Second Item" />        <Button Content="Third Item" />    </StackPanel></ScrollViewer> 

Related Articles

MSDN ‐ The Layout System

Last modified: 2009‐05‐27 08:38:49

Copyright (c) by Christian Moser, 2011.

Comments on this article

Show all comments

Mustansar

Commented on 2.February 2011

Assalam‐o‐alaikum A lot help for beginners, I am gona present it to my fellows tomorrow :﴿

Vandip

Commented on 3.March 2011

Awesome buddy ! Thankz a ton ! :﴿

Vandip

Commented on 3.March 2011

Awesome buddy ! Thankz a ton ! :﴿

gdemmi

Commented on 5.March 2011

Awewsome article!

Johnson

Commented on 10.March 2011

Very good article on layouts, thanks

  ► WPF Tutorial   ► WPF Application   ► WPF Binding   ► Datagrid WPF

rmc
Realce
As propriedades Margin e Padding pode ser usado para reservar algum espaço em volta de dentro do controle. A Margem é o espaço extra em torno do controle. O preenchimento é espaço extra dentro do controle. O preenchimento de um controle externo é a margem de um controle interno.
rmc
Realce
rmc
Realce
Altura e Largura Alltough não é uma forma recomendada, todos os controles fornecem uma altura e propriedade de largura para dar um elemento um tamanho fixo. A melhor maneira é usar as propriedades MinHeight, MaxHeight, MinWidth e MaxWidth para definir um intervalo aceitável. Se você definir a largura ou a altura para o próprio Auto tamanhos de controle para o tamanho do conteúdo.
rmc
Realce
rolagem Quando o conteúdo é demasiado grande para caber o tamanho disponível, você pode envolvê-lo em um ScrollViewer. O ScrollViewer usa duas barras de rolagem para escolher a área visível. A visibilidade das barras de deslocamento pode ser controlado pelas propriedades ScrollbarVisibility verticais e horizontais.
Page 3: WPF Tutorial _ Introduction to WPF Layout

17/12/2014 WPF Tutorial | Introduction to WPF Layout

http://www.wpftutorial.net/LayoutProperties.html 3/4

vs. RuntimeThemes

StylesTriggersStyleinheritanceOverridethedefaultStyle

ControlTemplatesDataTemplates

LocalizationEvaluate alocalizationmechanismLocalizationusing aMarkupExtension

InteractionBehaviorsDrag &Drop

Resources

2D Graphics

3D GraphicsIntroductionto WPF 3D

AnimationAdjust theFrame RateDebuggingAnimations

MultimediaSpeechSynthesizer

DocumentsFlowDocumentsInlineImages in aFlowDocument

Windows 7Task DialogJumplistsGlassWindows

InteroperabilityQueryScreenResolutionsAppresources &WinFormsIntegration

PerformanceTop 11 WPFPerformanceTips

ExpressionBlend

PrototypingwithSketchFlow

lalita patil

Commented on 25.March 2011

We learnt lot of things from this article,its so nice

Sanjay Patolia

Commented on 26.March 2011

Nice one it really gives good idea about using layout panels and use best practise out of it. :﴿

raja

Commented on 27.March 2011

hai its very good article

rashmi

Commented on 17.April 2011

Small, crisp. Nice one. Thanks

Om Prakash

Commented on 21.April 2011

Good, nice,helpful article...... Thanks Sir G

Regard : Om Prakash Bishnoi

MuhammadHanif

Commented on 20.May 2011

Great effort. Easy to understand.....Learning with out boring.....Really interesting.

manmohan

Commented on 6.June 2011

Great stuff to make us understand the usefullness of layout panel in a simpler way.

rahul

Commented on 8.June 2011

nice

Raj

Commented on 14.June 2011

nice article

zeceTeddy

Commented on 15.June 2011

Very informative post. Thanks for taking the time to share your view with us.

AnubhavRanjan

Commented on 29.July 2011

Good article. Must read before starting development in WPF.

AS

Commented on 2.August 2011

Nice and clear for beginners

expert

Commented on 16.August 2011

good job...this helped me a lot

Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?

Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?

Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?

Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?

Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?

Saj

Commented on 1.September 2011

Hi Mate, Is there a way to add WPF Window at a desired position, like if you have a panel when userclicks on buttons the new window opens in the middle panel or desired panel rather thancoming up as New Window ﴾more like MDI window approach﴿

Page 4: WPF Tutorial _ Introduction to WPF Layout

17/12/2014 WPF Tutorial | Introduction to WPF Layout

http://www.wpftutorial.net/LayoutProperties.html 4/4

AddinsHow toImportPhotoshopFiles

ToolsXAMLConvertersGraphicalDesignersUtilitiesXAMLEditors

UI Automation

Thanks

MEE

Commented on 23.September 2011

Excellent

Name

E‐Mail ﴾optional﴿

Comment

Post Comment