Поиск…


холст

Canvas - самая простая из панелей. Он помещает предметы в указанные Top/Left координаты.

<Canvas>
  <TextBlock 
    Canvas.Top="50" 
    Canvas.Left="50" 
    Text="This is located at 50, 50"/>
  <TextBlock 
    Canvas.Top="100"
    Canvas.Left="50"
    Width="150"
    Height="23"
    Text="This is located at 50, 100 with height 23 and width 150"/>
</Canvas>

DockPanel

DockPanel выравнивает элемент управления в соответствии со свойством док-станции в том порядке, в котором он находится в элементе управления.

ПРИМЕЧАНИЕ. DockPanel является частью среды WPF, но не поставляется с Silverlight / WinRT / UWP. Однако реализации с открытым исходным кодом легко найти.

<DockPanel LastChildFill="False">
  <!-- This will strech along the top of the panel -->
  <Button DockPanel.Dock="Top" Content="Top"/>
  <!-- This will strech along the bottom of the panel -->
  <Button DockPanel.Dock="Bottom" Content="Bottom"/>
  <!-- This will strech along the remaining space in the left of the panel -->
  <Button DockPanel.Dock="Left" Content="Left"/>
  <!-- This will strech along the remaining space in the right of the panel -->
  <Button DockPanel.Dock="Right" Content="Right"/>
  <!-- Since LastChildFill is false, this will be placed at the panel's right, to the left of the last button-->
  <Button DockPanel.Dock="Right" Content="Right"/>
</DockPanel>

<!-- When lastChildFill is true, the last control in the panel will fill the remaining space, no matter what Dock was set to it -->
<DockPanel LastChildFill="True">
  <!-- This will strech along the top of the panel -->
  <Button DockPanel.Dock="Top" Content="Top"/>
  <!-- This will strech along the bottom of the panel -->
  <Button DockPanel.Dock="Bottom" Content="Bottom"/>
  <!-- This will strech along the remaining space in the left of the panel -->
  <Button DockPanel.Dock="Left" Content="Left"/>
  <!-- This will strech along the remaining space in the right of the panel -->
  <Button DockPanel.Dock="Right" Content="Right"/>
  <!-- Since LastChildFill is true, this will fill the remaining space-->
  <Button DockPanel.Dock="Right" Content="Fill"/>
</DockPanel>

StackPanel

StackPanel помещает свои элементы управления один за другим. Он действует как панель док-станции со всеми док-станциями управления, установленными на одно значение.

<!-- The default StackPanel is oriented vertically, so the controls will be presented in order from top to bottom -->
<StackPanel>
  <Button Content="First"/>
  <Button Content="Second"/>
  <Button Content="Third"/>
  <Button Content="Fourth"/>
</StackPanel>

<!-- Setting the Orientation property to Horizontal will display the control in order from left to right (or right to left, according to the FlowDirection property) -->
<StackPanel Orientation="Horizontal">
  <Button Content="First"/>
  <Button Content="Second"/>
  <Button Content="Third"/>
  <Button Content="Fourth"/>
</StackPanel>

Чтобы складывать элементы снизу вверх, используйте панель док-станции.

сетка

Grid используется для создания табличных макетов.

Определение основных строк и столбцов

<Grid>
  <!-- Define 3 columns with width of 100 -->
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="100"/>
    <ColumnDefinition Width="100"/>
    <ColumnDefinition Width="100"/>
  </Grid.ColumnDefinitions>
  <!-- Define 3 rows with height of 50 -->
  <Grid.RowDefinitions>
    <RowDefinition Height="50"/>
    <RowDefinition Height="50"/>
    <RowDefinition Height="50"/>
  </Grid.RowDefinitions>
  <!-- This is placed at the top left (first row, first column) -->
  <Button 
      Grid.Column="0"
      Grid.Row="0"
      Content="Top Left"/>
  <!-- This is placed at the top left (first row, second column) -->
  <Button 
      Grid.Column="1"
      Grid.Row="0"
      Content="Top Center"/>
  <!-- This is placed at the center (second row, second column) -->
  <Button 
      Grid.Column="1"
      Grid.Row="1"
      Content="Center"/>
  <!-- This is placed at the bottom right (third row, third column) -->
  <Button 
      Grid.Column="2"
      Grid.Row="2"
      Content="Bottom Right"/>
</Grid>

ПРИМЕЧАНИЕ. Все следующие примеры будут использовать только столбцы, но также применимы к строкам .


Авторазмеры

Столбцы и строки могут быть определены с помощью «Авто» в виде их ширины / высоты. Авто размер займет столько места, сколько нужно для отображения его содержимого, и не более того.
Определения с автоматическим определением могут использоваться с определениями фиксированного размера.

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition Width="50"/>
  </Grid.ColumnDefinitions>
  <!-- This column won't take much space -->
  <Button Grid.Column="0" Content="Small"/>
  <!-- This column will take much more space -->
  <Button Grid.Column="1" Content="This text will be very long."/>
  <!-- This column will take exactly 50 px -->
  <Button Grid.Column="2" Content="This text will be cut"/>
</Grid>

Простые определения размера звезды

Столбцы и строки можно определить с помощью * качестве их ширины / высоты. Звездообразные строки / столбцы занимают столько места, сколько есть , независимо от его содержимого.
Определения размера звезды могут использоваться с фиксированными и автоматическими определениями. Размер звезды по умолчанию и, следовательно, ширина столбца или высота строки могут быть опущены.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="50"/>
    </Grid.ColumnDefinitions>
    <!-- This column will be as wide as it can -->
    <Button Grid.Column="0" Content="Small"/>
    <!-- This column will take exactly 50 px -->
    <Button Grid.Column="2" Content="This text will be cut"/>
</Grid>

Пропорциональные определения размера звезды

Помимо того, что звезда занимает столько места, как это возможно, определения звезд также пропорциональны друг другу. Если ничего не упоминается, каждое определение звезды займет столько же места, сколько и остальные в текущей сетке.

Тем не менее, можно определить соотношение между размерами разных определений, просто добавив к нему множитель. Таким образом, столбец, определяемый как 2* будет в два раза шире столбца, определенного как * . Ширина одной единицы рассчитывается путем деления доступного пространства на сумму множителей (если нет, если не считать 1).
Таким образом, сетка с 3 столбцами, определенная как * , 2* , * будет представлена ​​как 1/4, 1/2, 1/4.
И один с 2 столбцами, определенными как 2* , 3* будет представлен 2/5, 3/5.

Если в наборе есть автоматические или фиксированные определения, они будут вычисляться первыми, и после этого определения звезды будут занимать оставшееся пространство.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <!-- This column will be as wide as the third column -->
    <Button Grid.Column="0" Content="Small"/>
    <!-- This column will be twice as wide as the rest -->
    <Button Grid.Column="1" Content="This text will be very long."/>
    <!-- This column will be as wide as the first column -->
    <Button Grid.Column="2" Content="This text will may be cut"/>
</Grid>

Окно столбца / строки

Можно сделать контроль над его ячейкой, установив Row / ColumnSpan. Установленное значение - количество строк / столбцов th

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <!-- This control will streach across most of the grid -->
    <Button Grid.Column="0" Grid.ColumnSpan="2" Content="Small"/>
    <Button Grid.Column="2" Content="This text will may be cut"/>
</Grid>

WrapPanel

Оберточная панель действует аналогично панели стека. За исключением случаев, когда он распознает, что элементы будут превышать его размер, он затем привяжет их к новой строке / столбцу в зависимости от ориентации.


Горизонтальная ориентация

<WrapPanel Width="100">
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
</WrapPanel>

Вертикальная оберточная панель

<WrapPanel Height="70" Orientation="Vertical">
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
</WrapPanel>

UniformGrid

Равномерная сетка будет размещать все ее дети в макете сетки, каждый ребенок в своей собственной ячейке. Все ячейки будут иметь одинаковый размер. Это можно считать сокращением к сетке, где все определения строк и столбцов установлены на *


Строки и столбцы по умолчанию

По умолчанию UniformGrid попытается создать равное количество строк и столбцов. Когда строка станет длинной, она добавит новый столбец.

Этот код создаст сетку 3x3 с заполнением первых двух строк и последней с помощью одной кнопки:

<UniformGrid>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
</UniformGrid>

Указанные строки / столбцы

Вы можете указать UniformGrid точно, сколько строк и / или столбцов вы хотите иметь.

<UniformGrid Columns="2" >
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
</UniformGrid>

ПРИМЕЧАНИЕ. Если установлены как строки, так и столбцы, и больше детей, чем ячеек, последние дети в сетке не будут отображаться


Свойство FirstColumn

Когда свойство Columns установлено, вы можете установить свойство FirstColumn. Это свойство будет вводить x пустых ячеек в первую строку до отображения первого ребенка. Значение FirstColumn должно быть меньше числа Columns.

В этом примере первая кнопка будет отображаться в первом столбце первой строки:

<UniformGrid Columns="2" FirstColumn="1">
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
    <Button Content="Button"/>
</UniformGrid>

RelativePanel

RelativePanel был представлен в Windows 10 и используется в основном для поддержки адаптивных макетов, где дочерние элементы панели расположены по-разному в зависимости от доступного пространства. RelativePanel обычно используется с визуальными состояниями , которые используются для переключения конфигурации макета, адаптации к размеру экрана или окна, ориентации или использования. Элементы-потомки используют прикрепленные свойства, которые определяют, где они относятся к панели и друг другу.

<RelativePanel
    VerticalAlignment="Stretch"
    HorizontalAlignment="Stretch">
    <Rectangle
        x:Name="rectangle1"
        RelativePanel.AlignLeftWithPanel="True"
        Width="360"
        Height="50"
        Fill="Red"/>
    <Rectangle
        x:Name="rectangle2"
        RelativePanel.Below="rectangle1"
        Width="360"
        Height="50"
        Fill="Green" />
</RelativePanel>
<VisualStateManager.VisualStateGroups>
    <VisualStateGroup>
        <VisualState>
            <VisualState.StateTriggers>
                <!--VisualState to be triggered when window width is >=720 effective pixels.-->
                <AdaptiveTrigger
                    MinWindowWidth="720" />
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter
                    Target="rectangle2.(RelativePanel.Below)"
                    Value="{x:Null}" />
                <Setter
                    Target="rectangle2.(RelativePanel.RightOf)"
                    Value="rectangle1" />
                <Setter
                    Target="rectangle1.(RelativePanel.AlignLeftWithPanel)"
                    Value="False" />
                <Setter
                    Target="rectangle1.(RelativePanel.AlignVerticalCenterWithPanel)"
                    Value="True" />
                <Setter
                    Target="rectangle2.(RelativePanel.AlignVerticalCenterWithPanel)"
                    Value="True" />
            </VisualState.Setters>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>


Modified text is an extract of the original Stack Overflow Documentation
Лицензировано согласно CC BY-SA 3.0
Не связан с Stack Overflow