Passo a passo: Construindo um layout dinâmico

In dynamic positioning, you arrange child elements by specifying how they should be arranged and how they should wrap relative to their parent. You can also set windows and controls to expand automatically when their content expands. For more information, see Layout com absoluto e dinâmica posicionamento.

O WPF Designer for Visual Studio fornece muitos Panel controla esse suporte posicionamento dinâmico. Panel controls can be combined by adding one panel control as the child of another. You can use the following panel controls to position elements dynamically in your applications:

Observação importanteImportante

Whenever possible, it is preferable to use a dynamic layout. Dynamic layouts are the most flexible, adapt to content changes such as localization, and allow the end user the most control over their environment. To see an example of an absolute layout, see Passo a passo: Construindo um layout com base no posicionamento absoluto.

In this walkthrough, you perform the following tasks:

  • Create a WPF application.

  • Configure the default Grid panel control.

  • Add controls to the panel.

  • Test the layout.

The following illustration shows how your application will appear.

Um layout dinâmico

ObservaçãoObservação

Caixas de diálogo e comandos de menu que você vê podem diferir das descritas na Help dependendo das suas configurações ativas ou edição. Para alterar as configurações, escolha Import and Export Settings sobre o Ferramentas menu. For more information, see Trabalhando com configurações.

Pré-requisitos

You need the following components to complete this walkthrough:

  • Visual Studio 2010

Creating the Project

The first procedure is to create the project for the application.

To create the project

  1. Create a new WPF Application project in Visual Basic or Visual C# named DynamicLayout. For more information, see Como: Criar um novo projeto de aplicativo WPF.

    ObservaçãoObservação

    You will not write any code in this walkthrough. The language that you choose for your project is the language that is used for the code-behind pages in your application.

    MainWindow. XAML é aberto no WPF Designer.

  2. In Design view, select the window. For more information, see Como: Selecionar e mover elementos na superfície de design.

  3. In the Properties window, set the following properties for the Window:

    Property

    Value

    Width

    400

    Height

    200

    SizeToContent

    WidthAndHeight

    Dica

    You can also use the resize handles to resize the window in Design view.

  4. On the File menu, click Save All.

Configuring the Default Grid Panel Control

By default, the new WPF application contains a Window with a Grid panel. In this procedure you add four rows and four columns to the grid. You set the width of each column to *, so that the available width is divided evenly among the four columns. You set the height of three of the rows to Auto, so that they are sized to fit their content. You set the height of one of the rows to *, so that it uses the remaining available height.

To add a panel control

  1. In Design view, select the grid.

  2. (Optional) In the Properties window, locate the ShowGridLines property and select the check box.

    When the application runs, the gridlines will appear on the window. This is useful for debugging, but you should clear the ShowGridLines property check box for production code.

  3. In the Properties window, locate the ColumnDefinitions property, and click the ellipsis button in the property value column.

    The Collection Editor dialog box appears.

    1. Click Add four times to add four columns.

    2. Set the Width property of the first row to Auto.

    3. Set the Width property of the second row to *.

    4. Set the Width property of the third row to Auto.

    5. Set the Width property of the fourth row to Auto.

    6. Click OK to close the Collection Editor and return to the WPF Designer.

      Now there are four columns in the grid, but only one column appears. The columns whose Width properties are set to Auto are temporarily hidden because they do not have any content. For this walkthrough, that is fine. To avoid this in the future, you can use star sizing while you work, and change to Auto when you are done.

  4. In the Properties window, locate the RowDefinitions property, and click the ellipsis button in the property value column.

    The Collection Editor dialog box appears.

    1. Click Add four times to add four rows.

    2. Set the Height property of the first row to Auto.

    3. Set the Height property of the second row to Auto.

    4. Set the Height property of the third row to *.

    5. Set the Height property of the fourth row to Auto.

    6. Click OK to close the Collection Editor and return to the WPF Designer.

      Now there are four rows in the grid, but only one row appears. The rows whose Height properties are set to Auto are temporarily hidden because they do not have any content. For this walkthrough, that is fine. To avoid this in the future, you can use star sizing while you work, and change to Auto when you are done.

  5. On the File menu, click Save All.

Adding Controls to the Panel

Next you add controls to the panel and use the Column and Row attached properties of the Grid to position them dynamically.

To add controls to the panel

  1. From the Toolbox, in the Common group, drag a Label control onto the Grid.

  2. In the Properties window, set the following properties for the Label:

    Property

    Value

    Content

    Name:

    Grid.Column

    0

    Grid.ColumnSpan

    1

    Grid.Row

    0

    Grid.RowSpan

    1

    Width

    Auto

    Height

    23

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Top

    Margin

    20,20,10,10

  3. From the Toolbox, in the Common group, drag a Label control onto the Grid.

  4. In the Properties window, set the following properties for the Label:

    Property

    Value

    Content

    Password:

    Grid.Column

    0

    Grid.ColumnSpan

    1

    Grid.Row

    1

    Grid.RowSpan

    1

    Width

    Auto

    Height

    23

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Top

    Margin

    20,10,10,10

  5. From the Toolbox, in the Common group, drag a TextBox control onto the Grid.

  6. In the Properties window, set the following properties for the TextBox:

    Property

    Value

    Grid.Column

    1

    Grid.ColumnSpan

    3

    Grid.Row

    0

    Grid.RowSpan

    1

    Width

    Auto

    Height

    Auto

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Stretch

    Margin

    10,20,20,10

  7. From the Toolbox, in the Common group, drag a TextBox control onto the Grid.

  8. In the Properties window, set the following properties for the TextBox:

    Property

    Value

    Grid.Column

    1

    Grid.ColumnSpan

    3

    Grid.Row

    1

    Grid.RowSpan

    1

    Width

    Auto

    Height

    Auto

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Stretch

    Margin

    10,10,20,10

  9. From the Toolbox, in the Common group, drag a Button control onto the Grid.

  10. In the Properties window, set the following properties for the Button:

    Property

    Value

    Content

    OK

    Grid.Column

    2

    Grid.ColumnSpan

    1

    Grid.Row

    3

    Grid.RowSpan

    1

    Width

    75

    Height

    23

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Stretch

    Margin

    10,10,6,20

  11. From the Toolbox, in the Common group, drag a Button control onto the Grid.

  12. In the Properties window, set the following properties for the Button:

    Property

    Value

    Content

    Cancel

    Grid.Column

    3

    Grid.ColumnSpan

    1

    Grid.Row

    3

    Grid.RowSpan

    1

    Width

    75

    Height

    23

    HorizontalAlignment

    Stretch

    VerticalAlignment

    Stretch

    Margin

    6,10,20,20

  13. On the File menu, click Save All.

Testing the Layout

Finally you run the application and verify that the layout changes dynamically as the user resizes the window, and as the content of the controls expands beyond the size of the controls.

To test the layout

  1. On the Debug menu, click Start Debugging.

    The application starts and the window appears.

  2. In the Name text box, type randomly to fill the text box. When you reach the end of the text box, both the text box and the window expand to fit the text that you type.

  3. Close the window.

  4. On the Debug menu, click Start Debugging.

    The application starts and the window appears.

  5. Resize the window both vertically and horizontally.

    The columns expand evenly to use the available space. The text boxes stretch to fill the expanded columns. Three rows maintain their height, and the fourth row expands to use the available space.

  6. Close the window.

  7. In Design view, select the Name label.

  8. No Propriedades janela, altere a propriedade de conteúdo para Insira seu nome completo aqui:.

    In Design view, the label expands to fit the text.

  9. On the Debug menu, click Start Debugging.

    The application starts and the window appears. The label control displays the longer text.

  10. Close the window.

Putting it all Together

Este é o arquivo de MainWindow. XAML completo:

<Window x:Class="MainWindow"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="200" Width="400" SizeToContent="WidthAndHeight">
    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" Grid.Row="0" Margin="20,20,10,10" Width="Auto" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Name="Label1">Name:</Label>
        <Label Grid.Column="0" Grid.Row="1" Margin="20,10,10,10" Width="Auto" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Name="Label2">Password:</Label>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="10,20,20,10" Grid.ColumnSpan="3" Height="Auto" VerticalAlignment="Stretch" Name="TextBox1" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="10,10,20,10" Grid.ColumnSpan="3" Name="TextBox2" />
        <Button Grid.Column="2" Grid.Row="3" Margin="10,10,6,20" Width="75" Height="23" HorizontalAlignment="Stretch" Name="Button1">OK</Button>
        <Button Grid.Column="3" Grid.Row="3" Margin="6,10,20,20" Width="75" Height="23" Name="Button2">Cancel</Button>
    </Grid>
</Window>

Próximas etapas

You can experiment to learn how to achieve different effects with dynamic layouts by replacing the Grid panel in this walkthrough with the following panels:

Consulte também

Tarefas

Como: Criar um layout dinâmico

Walkthrough: Criando um aplicativo redimensionável usando o WPF Designer

Conceitos

Alinhamento no WPF Designer

Sistema de layout

Visão geral do WPF e do Silverlight Designer

Outros recursos

Walkthroughs de layout