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