简体   繁体   English

在可拉伸的WPF窗口中的一行上布置两个控件

[英]Layout two controls on a line in a stretchable WPF window

Here's a fairly common UI pattern: Text box that contains a path to the left, and a Browse button to the right of it. 这是一个相当常见的UI模式:文本框,其中包含一个位于左侧的路径和一个位于其右侧的“浏览”按钮。 If the window resizes, the button stays to the right, but the text box stretches to reveal more/less of the path. 如果调整窗口大小,则按钮将保持在右侧,但文本框会拉伸以显示更多/更少的路径。 So in the good old days of anchors, the button would be anchored to the right and the text box would be anchored both left and right. 因此,在锚定的美好年代,按钮将锚定在右侧,而文本框将同时锚定在左侧和右侧。

Trying to replicate this in WPF seems to be worryingly difficult. 试图在WPF中复制它似乎非常困难。

If I create a new window, it comes with a Grid layout by default. 如果我创建一个新窗口,则默认情况下它带有网格布局。 I place my text box to the left and size it appropriately, then place the button to its right. 我将文本框放置在左侧并适当调整其大小,然后将按钮放置在右侧。 HorizontalAlignment for the text box is Stretch and for the button it is Right. 文本框的Horizo​​ntalAlignment为拉伸,按钮为Right。

In my mind, this works as described, but in real life the text box doesn't resize at all, but instead tries to center itself in the window, while the button acts as expected. 在我看来,这是按说明的方式工作的,但是在现实生活中,文本框根本不会调整大小,而是尝试在窗口中居中放置,而按钮却按预期的那样工作。 What gives? 是什么赋予了?

Here is my XAML: 这是我的XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="241" d:DesignWidth="414" SizeToContent="WidthAndHeight">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Stretch" Name="textBox1" VerticalAlignment="Top" Margin="12,11,101,0" />
        <Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,11,12,0" Name="button1" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

You would create another GridControl with two columns, one with a fixed width for Browse button and another one for the TextBox . 您将创建另一个具有两列的GridControl ,其中一列具有用于Browse按钮的固定宽度,另一列具有用于TextBox宽度。

<Grid>            
    <Grid.ColumnDefinitions> 
        <ColumnDefinition />
        <ColumnDefinition Width="75" />
    </Grid.ColumnDefinitions>
    <TextBox Grid.Column="0" />
    <Button Grid.Column="1" />
</Grid>

You can use a DockPanel and set LastChildFill property to true to ensure that the textbox uses all the available space: 您可以使用DockPanel并将LastChildFill属性设置为true以确保文本框使用所有可用空间:

<DockPanel LastChildFill="true">
  <Button DockPanel.Dock="Right">Browse</Button>
  <TextBox>Content</TextBox>
</DockPanel>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM