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

7

我有一段XAML代码:

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

我该如何获得textBox的所有可用空间?

我想要做类似于这样的事情:

|[____________________][获取]|


2
WrapPanel的目的是什么? - John Fisher
我不知道有什么更好的方法来做这件事 :P - Neir0
4个回答

8
有很多方法可以实现这个目标,其中包括以下方式:
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>
  <TextBox />
  <Button Grid.Column="1">GetIt</Button>
</Grid>

谢谢!我可以问另一个问题吗?如何粘贴网格列。|[__________][获取]| |...................| |.......这里还有。| |.多行文本框。| |...................| - Neir0
哦,抱歉。我的评论失去了格式。 我的意思是这个:http://img708.imageshack.us/img708/2383/screengw.png - Neir0
Neir0 - 你正在尝试获得 DockPanel 设计的精确效果。你可以使用 Grid 来实现相同的效果,Grid 更加灵活,但需要更多的 XAML,并且如果需要添加或删除项,则需要维护 Row/Column/RowSpan/ColumnSpan 值。 - John Bowen

2

试试这个:

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

只需将按钮设置为所需的宽度,文本框就会填充其余空间。


感谢您的指正;已更正以正确处理右侧边距。但是,这需要在按钮宽度更改时更新边距。如果您经常更改间距,则两列是更好的解决方案。如果网格中有多个控件且不想创建嵌套网格来处理此类拆分,则使用边距更干净。


但在这种情况下,按钮位于文本框上方。 您可以在此处查看屏幕截图http://img214.imageshack.us/img214/918/screeneb.png - Neir0
这是一种技巧,我打赌它来自于学习如何在CSS中进行布局而不使用表格的方法。 - Robert Rossney
这也是 Blend 在你在网格中拖放和调整控件时会“猜测”的代码类型。 - Dan Bryant

2
最简单的方法是使用DockPanel而不是Grid(LastChildFill的默认值为true,但我在这里也添加了它以增加清晰度):
<DockPanel LastChildFill="True">
  <Button Content="GetIt" DockPanel.Dock="Right" />
  <TextBox ></TextBox>
</DockPanel>

2
以下是实现您所需布局的方法:

这里有一个实现您所需布局的方法:

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接