繁体   English   中英

如何让控件填满所有可用空间

[英]How to have a control fill all available space

我有一个xaml代码:

<Grid>
    <WrapPanel>
    <TextBox ></TextBox>
    <Button Content="GetIt" />
    </WrapPanel>
</Grid>

我怎样才能获得textBox的所有可用空间?

我想做那样的事情:

| [____________________] [GETIT] |

有许多方法可以实现,包括以下方法:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>
  <TextBox />
  <Button Grid.Column="1">GetIt</Button>
</Grid>

尝试这个:

<Grid>
    <TextBox HorizontalAlignment="Stretch" Margin="2,2,102,2"></TextBox>
    <Button HorizontalAlignment="Right" Width="100" Content="GetIt" />
</Grid>

只需使按钮具有所需的宽度,文本框将填满其余部分。


谢谢你的捕获; 在上面纠正以正确处理右边的保证金。 但是,这确实需要您在按钮宽度更改时更新边距。 如果您打算经常更改间距,则两列是更好的解决方案。 如果网格中有多个控件并且不想创建嵌套网格来处理这种拆分,则使用边距更清晰。

最简单的方法是使用DockPanel而不是Grid(LastChildFill的默认值为true,但为了清楚起见,我在此处添加了它):

<DockPanel LastChildFill="True">
  <Button Content="GetIt" DockPanel.Dock="Right" />
  <TextBox ></TextBox>
</DockPanel>

这是实现您正在寻找的布局的一种方法:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <Style TargetType="TextBox">
      <Setter Property="Margin" Value="2"/>
    </Style>
  </Page.Resources>
  <DockPanel>
    <DockPanel DockPanel.Dock="Top">
      <!-- Because the Button is fixed in size, you can divide the row it's 
      in using a DockPanel:  the Button is docked to the right edge, and the
      TextBox fills up the remaining available space. -->
      <Button Margin="2" Padding="2" DockPanel.Dock="Right">GetIt</Button>
      <TextBox />
    </DockPanel>
    <!-- Because the TextBoxes *aren't* fixed in size, you can't use docking,
    as it won't size them.  So put them in a Grid and use star sizing to
    divide the grid's vertical space into two equal parts.   The Grid will
    fill up the remainder of the (outer) DockPanel. -->
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <TextBox Grid.Row="0">Another TextBox</TextBox>
      <TextBox Grid.Row="1">Yet another TextBox</TextBox>
    </Grid>
  </DockPanel>
</Page>

暂无
暂无

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

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