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

时间:2010-03-13 17:34:12

标签: c# wpf xaml

我有一个xaml代码:

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

如何为textBox获取所有可用空间?

我想做类似的事情:

  

| [____________________] [GETIT] |

4 个答案:

答案 0 :(得分:7)

有很多方法可以实现,包括这一个:

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

答案 1 :(得分:3)

试试这个:

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

只需将按钮设置为所需宽度,文本框将填满其余部分。


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

答案 2 :(得分:2)

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

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

答案 3 :(得分: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>