- FrameworkElement.Margin Property
- Syntax
- XAML Values
- Property Value
- Remarks
- Margin Behavior and Layout
- Margin and Padding
- Animating a Margin
- Examples
- Version Information
- Silverlight
- Silverlight for Windows Phone
- Platforms
- Framework Element. Margin Property
- Definition
- Property Value
- Examples
- Remarks
- Margin behavior and layout
- Margin and Padding
- Framework Element. Margin Property
- Definition
- Property Value
- Examples
- Remarks
- Margin behavior and layout
- Margin and Padding
- Framework Element. Margin Property
- Definition
- Property Value
- Remarks
- XAML Attribute Usage
- XAML Values
- Framework Element. Margin Свойство
- Определение
- Значение свойства
- Комментарии
- Использование атрибута XAML XAML Attribute Usage
- Значения XAML XAML Values
FrameworkElement.Margin Property
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Gets or sets the outer margin of a FrameworkElement.
Namespace: В System.Windows
Assembly: В System.Windows (in System.Windows.dll)
Syntax
XAML Values
uniform
A value measured by pixels that specifies a uniform Thickness. The uniform value is applied to all four Thickness properties (Left, Top, Right, Bottom).
left+right
A value measured by pixels that specifies the Left and Right of a symmetrical Thickness.
top+bottom
A value measured by pixels that specifies the Top and Bottom of a symmetrical Thickness.
leftВ topВ rightВ bottom
Values measured by pixels that specify the four possible dimension properties of a Thickness structure (Left, Top, Right, Bottom).
In the XAML syntaxes shown previously, you can also use a space instead of a comma as the delimiter between values.
See Remarks for value type, value bounds and edge-case considerations that affect both code and XAML usages of Margin.
Property Value
Type: System.Windows.Thickness
Provides margin values for the object. The default value is a default Thickness with all properties (dimensions) equal to 0.
Remarks
Dependency property identifier field:В MarginProperty
The margin is the space between this object and other objects that will be adjacent when layout creates the UI. The other objects participating in layout might be peer objects (such as other objects in the collection of a common parent control), or might also be this object’s parent in the visual tree.
Margin can be set as discrete Thickness values instead of as a uniform value so that the margin around an object can be set asymmetrically. The Thickness structure itself supports string type conversion so that you can specify an asymmetric Margin in XAML attribute syntax. For example, in XAML, an object that has a margin specified as Margin=»15,10,0,10″ would have a margin of 15 pixels on the left, 10 on the top, 0 on the right, and 10 on the bottom.
The following illustration shows the effect of setting the Margin property.
Margin Behavior and Layout
A margin value greater than 0 applies space outside the layout’s ActualWidth and ActualHeight.
Margins are additive for peer objects in a layout; for example, two horizontally or vertically adjacent objects both with a margin of 30 set on the adjoining edge would have 60 pixels of space between them.
Objects that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the object’s content area. The content area will be constrained instead when layout is calculated. The only case where margins would be constrained also is if the content is already constrained all the way to zero. However, this behavior is ultimately controlled by the specific type that is interpreting Margin, as well as the layout container of that object.
Negative values for margin dimensions are permitted, but should be used with caution (and be aware that negative margins can be interpreted differently by different class layout implementations). Negative margins typically clip the content of the object in that direction.
Non-integral values for margin values are technically permitted, but should generally be avoided and are typically rounded by the default layout rounding behavior. See Layout Rounding.
There is no prescribed upper bound for margin dimensions, and it is possible (though rarely desirable) to set a margin that positions object content outside the Silverlight content area so that the object content does not display in view.
Margin and Padding
A related concept is padding. For an object and its bounding box, the margin is extra space that is allocated to the outside of the bounding box when the UI element is contained and rendered. Padding is the area inside the bounding box, and affects the layout of any additional content or child objects inside the element. FrameworkElement does not yet define a content model; therefore, the properties for padding are instead defined by subclasses that do define a content model. The most common such property is TextBlock.Padding. Other properties are TextBlock.Padding and Border.Padding. For more information about the relationship between margin and padding, see Silverlight Layout System.
Animating a Margin
Silverlight does not currently support direct animation of a margin, because there is no ThicknessAnimation type in Silverlight (the type is located in WPF). Border has the same issue because BorderThickness also uses the Thickness type. One possible workaround is to wrap the element in a transparent panel and animate relevant Double properties of the panel.
Examples
The following example sets margins for various elements in XAML.
The following example shows how to set a Margin in code, by creating a new Thickness inline. This is shown in the context where setting Margin in code might be necessary: when you are creating the full UI element where the Margin is being set with code instead of XAML.
Version Information
Silverlight
Supported in: 5, 4, 3
Silverlight for Windows Phone
Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0
Platforms
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
Framework Element. Margin Property
Definition
Gets or sets the outer margin of a FrameworkElement.
Property Value
Provides margin values for the object. The default value is a default Thickness with all properties (dimensions) equal to 0.
Examples
This example sets Margin in code as part of a larger scenario of creating a UI element at run time, and then setting various layout-related properties. This is often done prior to adding a new element to an existing XAML UI page’s object tree. In this case several Margin properties are set using a new Thickness created with the uniform-value constructor.
Remarks
Margin behavior and layout
A margin value greater than 0 applies space outside the object’s ActualWidth and ActualHeight.
Margins are additive for peer objects in a layout; for example, two horizontally or vertically adjacent objects both with a margin of 30 set on the adjoining edge would have 60 pixels of space between them.
Objects that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the object’s content area. The content area will be constrained instead when layout is calculated. The only case where margins would be constrained also is if the content is already constrained all the way to zero. However, this behavior is ultimately controlled by the specific type that is interpreting Margin, as well as the layout container of that object.
Negative values for margin dimensions are permitted, but should be used with caution (and be aware that negative margins can be interpreted differently by different class layout implementations). Negative margins typically clip the content of the object in that direction.
Non-integral values for margin values are technically permitted, but should typically be avoided.
Margin and Padding
A related concept is padding. For an object and its bounding box, the margin is extra space that is allocated to the outside of the bounding box when the UI element is contained and rendered. Padding is the area inside the bounding box, and affects the layout of any additional content or child objects inside the element. FrameworkElement does not define a padding property, However, several derived classes do define a Padding property. These include:
Framework Element. Margin Property
Definition
Gets or sets the outer margin of a FrameworkElement.
Property Value
Provides margin values for the object. The default value is a default Thickness with all properties (dimensions) equal to 0.
Examples
This example sets Margin in code as part of a larger scenario of creating a UI element at run time, and then setting various layout-related properties. This is often done prior to adding a new element to an existing XAML UI page’s object tree. In this case several Margin properties are set using a new Thickness created with the uniform-value constructor.
Remarks
Margin behavior and layout
A margin value greater than 0 applies space outside the object’s ActualWidth and ActualHeight.
Margins are additive for peer objects in a layout; for example, two horizontally or vertically adjacent objects both with a margin of 30 set on the adjoining edge would have 60 pixels of space between them.
Objects that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the object’s content area. The content area will be constrained instead when layout is calculated. The only case where margins would be constrained also is if the content is already constrained all the way to zero. However, this behavior is ultimately controlled by the specific type that is interpreting Margin, as well as the layout container of that object.
Negative values for margin dimensions are permitted, but should be used with caution (and be aware that negative margins can be interpreted differently by different class layout implementations). Negative margins typically clip the content of the object in that direction.
Non-integral values for margin values are technically permitted, but should typically be avoided.
Margin and Padding
A related concept is padding. For an object and its bounding box, the margin is extra space that is allocated to the outside of the bounding box when the UI element is contained and rendered. Padding is the area inside the bounding box, and affects the layout of any additional content or child objects inside the element. FrameworkElement does not define a padding property, However, several derived classes do define a Padding property. These include:
Framework Element. Margin Property
Definition
Gets or sets the outer margin of an element.
Property Value
Provides margin values for the element. The default value is a Thickness with all properties equal to 0 (zero).
Remarks
The margin is the space between this element and other elements that will be adjacent when layout creates the user interface (UI). Shared elements might be peer elements (such as other elements in the collection of a common parent control), or might also be this element’s parent.
Margin is set as a Thickness structure rather than as a number so that the margin can be set asymmetrically. The Thickness structure itself supports string type conversion so that you can specify an asymmetric Margin in XAML attribute syntax also.
A non-zero margin applies space outside the element layout’s ActualWidth and ActualHeight.
Margins are additive for sibling elements in a layout; for example, two adjacent elements both with a margin of 30 set on the adjoining edge would have 60 units of space between them.
Elements that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the element content area. The element content area will be constrained instead when layout is calculated. The only case where margins would be constrained also is if the content is already constrained all the way to zero.
XAML Attribute Usage
XAML Values
left, top, right, bottom
Number values between 0 and PositiveInfinity that specify the four possible dimension properties of a Thickness structure.
The attribute usage will also accept abbreviated values that apply in the order provided, symmetrically and logically. For instance, Margin=»20″ will be interpreted to mean a Thickness with all properties set to 20. Margin=»20,50″ will be interpreted to mean a Thickness with Left and Right set to 20, and Top and Bottom set to 50.
The default unit for a Thickness measure is device-independent unit (1/96th inch). You can also specify other units by appending the unit type strings cm , in , or pt to any measure.
Number values provided as XAML attributes need not specify decimal points (0 is acceptable, does not have to be provided as 0.0). For more information on Extensible Application Markup Language (XAML) usage, see Thickness.
thicknessReference
An object reference to an existing Thickness. This might be a > , a , or > reference. For more information on Extensible Application Markup Language (XAML) usage, see Thickness.
Framework Element. Margin Свойство
Определение
Получает или задает значение внешнего поля элемента. Gets or sets the outer margin of an element.
Значение свойства
Предоставляет значения полей для элемента. Provides margin values for the element. Значение по умолчанию — Thickness. Все свойства равны 0 (нулю). The default value is a Thickness with all properties equal to 0 (zero).
Комментарии
Поле — это пространство между этим элементом и другими элементами, которые будут смежными, когда макет создаст пользовательский интерфейс. The margin is the space between this element and other elements that will be adjacent when layout creates the user interface (UI). Общие элементы могут быть одноранговыми (например, другими элементами в коллекции общего родительского элемента управления) или же родительским элементом. Shared elements might be peer elements (such as other elements in the collection of a common parent control), or might also be this element’s parent.
Margin задается как Thickness структура, а не как число, чтобы поле можно было установить асимметрично. Margin is set as a Thickness structure rather than as a number so that the margin can be set asymmetrically. ThicknessСама структура поддерживает преобразование строкового типа, поэтому можно также указать асимметричную Margin в синтаксисе атрибута XAML. The Thickness structure itself supports string type conversion so that you can specify an asymmetric Margin in XAML attribute syntax also.
Ненулевое поле применяет пространство за пределами макета элемента ActualWidth и ActualHeight . A non-zero margin applies space outside the element layout’s ActualWidth and ActualHeight.
Поля являются аддитивными для одноуровневых элементов в макете. Например, два соседних элемента с полем, равным 30, задаются на соседнем крае, будут иметь 60 единиц пространства между ними. Margins are additive for sibling elements in a layout; for example, two adjacent elements both with a margin of 30 set on the adjoining edge would have 60 units of space between them.
Элементы, имеющие набор полей, обычно не ограничивают размер, указанный, Margin Если выделенное пространство прямоугольника недостаточно велико для поля и области содержимого элемента. Elements that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the element content area. Вместо этого область содержимого элемента будет ограничена при вычислении макета. The element content area will be constrained instead when layout is calculated. Единственный случай, когда поля будут ограничены, также имеет значение, если содержимое уже ограничено нулем. The only case where margins would be constrained also is if the content is already constrained all the way to zero.
Использование атрибута XAML XAML Attribute Usage
Значения XAML XAML Values
слева, сверху, справа, снизу left, top, right, bottom
Числовые значения от 0 до PositiveInfinity , которые указывают четыре возможных свойства измерения Thickness структуры. Number values between 0 and PositiveInfinity that specify the four possible dimension properties of a Thickness structure.
Использование атрибута также позволит принимать сокращенные значения, которые применяются в указанном порядке (симметрично и логически). The attribute usage will also accept abbreviated values that apply in the order provided, symmetrically and logically. Например, Margin=»20″ будет интерпретироваться как значение Thickness со всеми свойствами, равными 20. For instance, Margin=»20″ will be interpreted to mean a Thickness with all properties set to 20. Margin=»20,50″ будет интерпретироваться как Thickness с параметром и равным Left Right 20, а Top также Bottom задано значение 50. Margin=»20,50″ will be interpreted to mean a Thickness with Left and Right set to 20, and Top and Bottom set to 50.
Единица по умолчанию для Thickness меры — независимая от устройства единица (1/1/96 дюйма). The default unit for a Thickness measure is device-independent unit (1/96th inch). Кроме того, можно указать другие единицы, добавив строки типа единиц cm , in или pt в любую меру. You can also specify other units by appending the unit type strings cm , in , or pt to any measure.
Числовые значения, предоставленные как атрибуты XAML, не должны указывать десятичные разделители (0 является приемлемым, не обязательно предоставляться как 0,0). Number values provided as XAML attributes need not specify decimal points (0 is acceptable, does not have to be provided as 0.0). Дополнительные сведения об использовании XAML (XAML) см. в разделе Thickness . For more information on Extensible Application Markup Language (XAML) usage, see Thickness.
сиккнессреференце thicknessReference
Ссылка на существующий объект Thickness . An object reference to an existing Thickness. Это может быть > , > ссылка или. This might be a > , a , or > reference. Дополнительные сведения об использовании XAML (XAML) см. в разделе Thickness . For more information on Extensible Application Markup Language (XAML) usage, see Thickness.