Windows 10 window padding

Alignment, margin, padding

In UWP apps, most user interface (UI) elements inherit from the FrameworkElement class. Every FrameworkElement has dimensions, alignment, margin, and padding properties, which influence layout behavior. The following guidance provides an overview of how to use these layout properties to make sure your app’s UI is legible and easy to use in any context.

Dimensions (Height, Width)

Proper sizing ensures all content is clear and legible. Users shouldn’t have to scroll or zoom to decipher primary content.

Height and Width specify the size of an element. The default values are mathematically NaN (Not A Number). You can set fixed values measured in effective pixels, or you can use Auto or proportional sizing for fluid behavior.

ActualHeight and ActualWidth are read-only properties that provide the size of an element at runtime. If fluid layouts grow or shrink, then the values change in a SizeChanged event. Note that a RenderTransform will not change the ActualHeight and ActualWidth values.

FontSize and other text properties control layout size for text elements. While text elements don’t have explicitly declared dimensions, they do have calculated ActualWidth and ActualHeight.

Alignment

Alignment makes your UI look neat, organized, and balanced and can also be used to establish visual hierarchy and relationships.

HorizontalAlignment and VerticalAlignment specify how an element should be positioned within its parent container.

  • The values for HorizontalAlignment are Left, Center, Right, and Stretch.
  • The values for VerticalAlignment are Top, Center, Bottom, and Stretch.

Stretch is the default for both properties, and elements fill all of the space they’re provided in the parent container. Real-number Height and Width cancel a Stretch value, which will instead act as a Center value. Some controls, like Button, override the default Stretch value in their default style.

Alignment can affect clipping within a layout panel. For example, with HorizontalAlignment=»Left» , the right side of the element gets clipped if the content is larger than the ActualWidth.

Text elements use the TextAlignment property. Generally, we recommend using left-alignment, the default value. For more information about styling text, see Typography.

Margin and padding

Margin and padding properties keep UI from looking too cluttered or too sparse, and they can also make it easier to use certain inputs like pen and touch. Here’s an illustration displaying margins and padding for a container and its content.

Margin

Margin controls the amount of empty space around an element. Margin does not add pixels to ActualHeight and ActualWidth and is not considered part of the element for hit testing and sourcing input events.

Margin values can be uniform or distinct. With Margin=»20″ , a uniform margin of 20 pixels would be applied to the element on the left, top, right, and bottom sides. With Margin=»0,10,5,25″ , the values are applied to the left, top, right, and bottom (in that order).

Margins are additive. If two elements both specify a uniform margin of 10 pixels and are adjacent peers in any orientation, the distance between them is 20 pixels.

Negative margins are permitted. However, using a negative margin can often cause clipping, or overdraws of peers, so it’s not a common technique to use negative margins.

Margin values are constrained last, so be careful with margins because containers can clip or constrain elements. A Margin value could be the cause of an element not appearing to render; with a Margin applied, an element’s dimension can be constrained to 0.

Padding

Padding controls the amount of space between the inner border of an element and its child content or elements. A positive Padding value decreases the content area of the element.

Unlike Margin, Padding is not a property of FrameworkElement. There are several classes which each define their own Padding property:

  • Control.Padding: inherits to all Control derived classes. Not all controls have content, so for those controls, setting the property does nothing. If the control has a border, the padding applies inside that border.
  • Border.Padding: defines space between the rectangle line created by BorderThickness/BorderBrush and the Child element.
  • ItemsPresenter.Padding: contributes to appearance of the items in item controls, placing the specified padding around each item.
  • TextBlock.Padding and RichTextBlock.Padding: expand the bounding box around the text of the text element. These text elements don’t have a Background, so it can be visually difficult to see. For that reason, use Margin settings on Block containers instead.

In each of these cases, elements also have a Margin property. If both Margin and Padding are applied, they are additive: the apparent distance between an outer container and any inner content will be margin plus padding.

Example

Let’s look at the effects of Margin and Padding on real controls. Here’s a TextBox inside of a Grid with the default Margin and Padding values of 0.

Here’s the same TextBox and Grid with Margin and Padding values on the TextBox as shown in this XAML.

Style resources

You don’t have to set each property value individually on a control. It’s typically more efficient to group property values into a Style resource and apply the Style to a control. This is especially true when you need to apply the same property values to many controls. For more info about using styles, see XAML styles.

Читайте также:  Minecraft windows 10 текстурпаки

General recommendations

Only apply measurement values to certain key elements and use fluid layout behavior for the other elements. This provides for responsive UI when the window width changes.

If you do use measurement values, all dimensions, margins, and padding should be in increments of 4 epx. When UWP uses effective pixels and scaling to make your app legible on all devices and screen sizes, it scales UI elements by multiples of 4. Using values in increments of 4 results in the best rendering by aligning with whole pixels.

For small window widths (less than 640 pixels), we recommend 12 epx gutters, and for larger window widths, we recommend 24 epx gutters.

Text Block. Padding Property

Definition

Gets or sets a value that indicates the thickness of padding space between the boundaries of the content area, and the content displayed by a TextBlock.

Property Value

A Thickness structure specifying the amount of padding to apply, in device independent pixels. The default is NaN.

Examples

The following example shows how to set the Padding attribute of a TextBlock element.

The following example shows how to set the Padding property programmatically.

Remarks

Padding can be described as uniform in all directions ( Padding=»10″ ), or as four distinct values that represent left, top, right, and bottom padding independently ( Padding=»5,0,10,20″ ).

If a specified padding thickness exceeds the corresponding content area dimension (for example, the sum of the left and right padding widths exceeds the content area width), the thickness of the padding is proportionally reduced to be no greater than the relevant content area dimension.

XAML Attribute Usage

XAML Values

uniformThickness
String representation of a single Double value to apply uniformly to all four thickness dimensions. For example, a value of «10» is equivalent to a value of «10,10,10,10» . An unqualified value is measured in device independent pixels. Strings need not explicitly include decimal points.

independentThickness
String representation of four ordered Double values corresponding to independent thickness dimensions for left, top, right, and bottom, in this order. The four values must be separated with commas; spaces are not allowed. For example, «5,10,15,20» results in 5 pixels of padding to the left of content, 10 pixels of padding above content, 15 pixels of padding to the right of content, and 20 pixels of padding below the content.

qualifiedUniformThickness
A value described by uniformThickness followed by one of the following unit specifiers: px , in .

px (default) is device-independent units (1/96th inch per unit)

in is inches; 1in==96px

For example, «1in» provides uniform padding of 1 inch in all directions.

qualifiedIndependentThickness
A value described by independentThickness, with each independent value followed by one of the following unit specifiers: px , in .

px (default) is device-independent units (1/96th inch per unit)

in is inches; 1in==96px

For example, «1.5in,0.8in,1.5in,0.8in» . Unit specifiers may be mixed or omitted from one or more values.

Общие сведения о свойствах Alignment, Margin, Padding Alignment, Margins, and Padding Overview

FrameworkElementКласс предоставляет несколько свойств, которые используются для точного позиционирования дочерних элементов. The FrameworkElement class exposes several properties that are used to precisely position child elements. В этом разделе обсуждаются четыре наиболее важных свойства: HorizontalAlignment , Margin , Padding и VerticalAlignment . This topic discusses four of the most important properties: HorizontalAlignment, Margin, Padding, and VerticalAlignment. Очень важно иметь представление о результатах применения этих свойств, поскольку они обеспечивают основу для управления положением элементов в приложениях Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) . The effects of these properties are important to understand, because they provide the basis for controlling the position of elements in Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) applications.

Введение в позиционирование элементов Introduction to Element Positioning

Существуют разные способы позиционирования элементов с помощью WPF WPF . There are numerous ways to position elements using WPF WPF . Однако достижение идеального макета выходит за рамки простого выбора правильного Panel элемента. However, achieving ideal layout goes beyond simply choosing the right Panel element. Точное управление размещением требует понимания HorizontalAlignment Margin свойств,, Padding и VerticalAlignment . Fine control of positioning requires an understanding of the HorizontalAlignment, Margin, Padding, and VerticalAlignment properties.

На следующем рисунке показан сценарий макета, использующий несколько свойств размещения. The following illustration shows a layout scenario that utilizes several positioning properties.

На первый взгляд, Button элементы на этом рисунке могут показаться случайными. At first glance, the Button elements in this illustration may appear to be placed randomly. На самом деле их положение точно контролируется с помощью сочетания полей, выравнивания и заполнения. However, their positions are actually precisely controlled by using a combination of margins, alignments, and padding.

В следующем примере демонстрируется создание макета, показанного на предыдущем рисунке. The following example describes how to create the layout in the preceding illustration. BorderЭлемент инкапсулирует родителя StackPanel , Padding значение которого равно 15 аппаратно-независимых пикселей. A Border element encapsulates a parent StackPanel, with a Padding value of 15 device independent pixels. Эти учетные записи для узких LightBlue полос, охватывающих дочерний элемент StackPanel . This accounts for the narrow LightBlue band that surrounds the child StackPanel. Дочерние элементы элемента StackPanel используются для иллюстрации каждого из различных свойств позиционирования, подробно описанных в этом разделе. Child elements of the StackPanel are used to illustrate each of the various positioning properties that are detailed in this topic. ButtonДля демонстрации свойств и используются три элемента Margin HorizontalAlignment . Three Button elements are used to demonstrate both the Margin and HorizontalAlignment properties.

Читайте также:  Звуковой драйвер realtek для windows 10 64 bit asus

Следующая схема обеспечивает подробное представление различных свойств размещения, примененных в предыдущем примере. The following diagram provides a close-up view of the various positioning properties that are used in the preceding sample. В последующих разделах этой статьи более подробно описывается использование каждого свойства размещения. Subsequent sections in this topic describe in greater detail how to use each positioning property.

Общие сведения о свойствах Alignment Understanding Alignment Properties

HorizontalAlignmentСвойства и VerticalAlignment описывают, как дочерний элемент должен располагаться в выделенном пространстве макета родительского элемента. The HorizontalAlignment and VerticalAlignment properties describe how a child element should be positioned within a parent element’s allocated layout space. При совместном использовании этих свойств можно точно расположить дочерние элементы. By using these properties together, you can position child elements precisely. Например, дочерние элементы DockPanel могут задавать четыре различных выравнивания по горизонтали: Left , Right , или Center , чтобы Stretch заполнить доступное пространство. For example, child elements of a DockPanel can specify four different horizontal alignments: Left, Right, or Center, or to Stretch to fill available space. Аналогичные значения доступны для вертикального размещения. Similar values are available for vertical positioning.

Явно заданный параметр Height и Width свойства элемента имеют приоритет над Stretch значением свойства. Explicitly-set Height and Width properties on an element take precedence over the Stretch property value. Попытка установить Height , Width и значение, если HorizontalAlignment Stretch Stretch запрос пропускается. Attempting to set Height, Width, and a HorizontalAlignment value of Stretch results in the Stretch request being ignored.

Свойство HorizontalAlignment HorizontalAlignment Property

HorizontalAlignmentСвойство объявляет характеристики выравнивания по горизонтали, которые применяются к дочерним элементам. The HorizontalAlignment property declares the horizontal alignment characteristics to apply to child elements. В следующей таблице показаны все возможные значения HorizontalAlignment Свойства. The following table shows each of the possible values of the HorizontalAlignment property.

Член Member Описание Description
Left Дочерние элементы выравниваются по левому краю выделенного пространства макета родительского элемента. Child elements are aligned to the left of the parent element’s allocated layout space.
Center Дочерние элементы выравниваются по центру выделенного пространства макета родительского элемента. Child elements are aligned to the center of the parent element’s allocated layout space.
Right Дочерние элементы выравниваются по правому краю выделенного пространства макета родительского элемента. Child elements are aligned to the right of the parent element’s allocated layout space.
Stretch (по умолчанию) Stretch (Default) Дочерние элементы растягиваются для заполнения выделенного пространства макета родительского элемента. Child elements are stretched to fill the parent element’s allocated layout space. Явные Width Height значения и имеют приоритет. Explicit Width and Height values take precedence.

В следующем примере показано, как применить HorizontalAlignment свойство к Button элементам. The following example shows how to apply the HorizontalAlignment property to Button elements. Показаны все значения атрибутов, чтобы проиллюстрировать различные режимы отрисовки. Each attribute value is shown, to better illustrate the various rendering behaviors.

Приведенный выше код создает макет, похожий на следующий рисунок. The preceding code yields a layout similar to the following image. На HorizontalAlignment рисунке видны эффекты позиционирования каждого значения. The positioning effects of each HorizontalAlignment value are visible in the illustration.

Свойство VerticalAlignment VerticalAlignment Property

VerticalAlignmentСвойство описывает характеристики вертикального выравнивания, применяемые к дочерним элементам. The VerticalAlignment property describes the vertical alignment characteristics to apply to child elements. В следующей таблице показаны все возможные значения VerticalAlignment Свойства. The following table shows each of the possible values for the VerticalAlignment property.

Член Member Описание Description
Top Дочерние элементы выравниваются по верхнему краю выделенного пространства макета родительского элемента. Child elements are aligned to the top of the parent element’s allocated layout space.
Center Дочерние элементы выравниваются по центру выделенного пространства макета родительского элемента. Child elements are aligned to the center of the parent element’s allocated layout space.
Bottom Дочерние элементы выравниваются по нижнему краю выделенного пространства макета родительского элемента. Child elements are aligned to the bottom of the parent element’s allocated layout space.
Stretch (по умолчанию) Stretch (Default) Дочерние элементы растягиваются для заполнения выделенного пространства макета родительского элемента. Child elements are stretched to fill the parent element’s allocated layout space. Явные Width Height значения и имеют приоритет. Explicit Width and Height values take precedence.

В следующем примере показано, как применить VerticalAlignment свойство к Button элементам. The following example shows how to apply the VerticalAlignment property to Button elements. Показаны все значения атрибутов, чтобы проиллюстрировать различные режимы отрисовки. Each attribute value is shown, to better illustrate the various rendering behaviors. Для целей этого примера Grid элемент с видимыми линиями сетки используется в качестве родителя, чтобы лучше проиллюстрировать поведение макета для каждого значения свойства. For purposes of this sample, a Grid element with visible gridlines is used as the parent, to better illustrate the layout behavior of each property value.

Приведенный выше код создает макет, похожий на следующий рисунок. The preceding code yields a layout similar to the following image. На VerticalAlignment рисунке видны эффекты позиционирования каждого значения. The positioning effects of each VerticalAlignment value are visible in the illustration.

Основные сведения о свойствах Margin Understanding Margin Properties

MarginСвойство описывает расстояние между элементом и его дочерними или одноранговыми узлами. The Margin property describes the distance between an element and its child or peers. Margin значения могут быть однородными с помощью синтаксиса, такого как Margin=»20″ . Margin values can be uniform, by using syntax like Margin=»20″ . Благодаря этому синтаксису Margin элементу будет применено универсальное из 20 аппаратно независимых пикселей. With this syntax, a uniform Margin of 20 device independent pixels would be applied to the element. Margin значения могут также иметь форму из четырех различных значений, каждое из которых описывает отдельное поле для применения к левым, верхним, правым и нижним (в этом порядке), например Margin=»0,10,5,25″ . Margin values can also take the form of four distinct values, each value describing a distinct margin to apply to the left, top, right, and bottom (in that order), like Margin=»0,10,5,25″ . Правильное использование Margin свойства обеспечивает очень точное управление позицией отрисовки элемента и позицией отрисовки его соседних элементов и потомков. Proper use of the Margin property enables very fine control of an element’s rendering position and the rendering position of its neighbor elements and children.

Ненулевое поле применяет пространство за пределами элемента ActualWidth и ActualHeight . A non-zero margin applies space outside the element’s ActualWidth and ActualHeight.

В следующем примере показано, как применять однородные поля вокруг группы Button элементов. The following example shows how to apply uniform margins around a group of Button elements. ButtonЭлементы размещаются равномерно с использованием буфера полей размером в десять пикселей в каждом направлении. The Button elements are spaced evenly with a ten-pixel margin buffer in each direction.

Во многих случаях универсальные поля не подходят. In many instances, a uniform margin is not appropriate. В этих случаях можно применять неоднородные интервалы. In these cases, non-uniform spacing can be applied. В следующем примере показано применение неоднородных полей к дочерним элементам. The following example shows how to apply non-uniform margin spacing to child elements. Поля описываются в следующем порядке: слева, сверху, справа, снизу. Margins are described in this order: left, top, right, bottom.

Основные сведения о свойстве Padding Understanding the Padding Property

Заполнение аналогично Margin в большинстве случаев. Padding is similar to Margin in most respects. Свойство Padding предоставляется только в нескольких классах, в основном как удобство: Block ,, Border Control и TextBlock — примеры классов, предоставляющих свойство заполнения. The Padding property is exposed on only on a few classes, primarily as a convenience: Block, Border, Control, and TextBlock are samples of classes that expose a Padding property. PaddingСвойство увеличивает эффективный размер дочернего элемента на указанное Thickness значение. The Padding property enlarges the effective size of a child element by the specified Thickness value.

В следующем примере показано, как применить Padding к родительскому Border элементу. The following example shows how to apply Padding to a parent Border element.

Использование свойств Alignment, Margin и Padding в приложении Using Alignment, Margins, and Padding in an Application

HorizontalAlignment, Margin , Padding и VerticalAlignment предоставляют элемент управления положением, необходимый для создания сложного элемента пользовательский интерфейс user interface (UI) . HorizontalAlignment, Margin, Padding, and VerticalAlignment provide the positioning control necessary to create a complex пользовательский интерфейс user interface (UI) . Эффекты каждого свойства позволяют изменить размещение дочерних элементов, обеспечивая гибкость создания динамических приложений и интерфейсов пользователя. You can use the effects of each property to change child-element positioning, enabling flexibility in creating dynamic applications and user experiences.

В следующем примере демонстрируются понятия, описанные в этом разделе. The following example demonstrates each of the concepts that are detailed in this topic. Основываясь на инфраструктуре в первом примере этого раздела, в этом примере элемент добавляется Grid в качестве дочернего элемента Border в первом примере. Building on the infrastructure found in the first sample in this topic, this example adds a Grid element as a child of the Border in the first sample. Padding применяется к родительскому Border элементу. Padding is applied to the parent Border element. GridИспользуется для разделения пространства между тремя дочерними StackPanel элементами. The Grid is used to partition space between three child StackPanel elements. Button элементы снова используются для отображения различных эффектов Margin и HorizontalAlignment . Button elements are again used to show the various effects of Margin and HorizontalAlignment. TextBlock к каждому элементу добавляются элементы ColumnDefinition для лучшего определения различных свойств, применяемых к Button элементам в каждом столбце. TextBlock elements are added to each ColumnDefinition to better define the various properties applied to the Button elements in each column.

При компиляции приведенное выше приложение создает UI UI , который показан на рисунке ниже. When compiled, the preceding application yields a UI UI that looks like the following illustration. Влияние различных значений свойств очевидно в интервале между элементами, а значимые значения свойств для элементов в каждом столбце отображаются в TextBlock элементах. The effects of the various property values are evident in the spacing between elements, and significant property values for elements in each column are shown within TextBlock elements.

Дальнейшие действия What’s Next

Свойства позиционирования, определенные FrameworkElement классом, обеспечивают точное управление размещением элементов в WPF WPF приложениях. Positioning properties defined by the FrameworkElement class enable fine control of element placement within WPF WPF applications. Вы получаете в свое распоряжение несколько способов, позволяющих более эффективно размещать элементы с помощью WPF WPF . You now have several techniques you can use to better position elements using WPF WPF .

Доступны дополнительные ресурсы, в которых макет WPF WPF рассматривается более подробно. Additional resources are available that explain WPF WPF layout in greater detail. Раздел Обзор панелей содержит более подробные сведения о различных Panel элементах. The Panels Overview topic contains more detail about the various Panel elements. В разделе Пошаговое руководство. мое первое классическое приложение WPF содержит дополнительные методы, которые используют элементы макета для позиционирования компонентов и привязки их действий к источникам данных. The topic Walkthrough: My first WPF desktop application introduces advanced techniques that use layout elements to position components and bind their actions to data sources.

Читайте также:  Нет заставки starting windows
Оцените статью