2010-03-13 71 views
7

我有一個XAML代碼:如何有一個控制填滿所有可用的空間

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

我怎樣才能獲得的textBox中的所有可用空間?

我想要做這樣的事情:

| [____________________] [GETIT] |

+2

WrapPanel的目的是什麼? – 2010-03-13 17:47:28

+0

我只是不知道什麼是更好的方式來做到這一點:P – Neir0 2010-03-13 18:16:13

回答

7

有許多方法可以做到這一點,包括這一個:

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

謝謝!我可以問另一個問題嗎?我如何粘貼網格列。 | [__________] [GetIt] | | ................... | | ...這是另一個。| | .multyline文本框。| | ................... | – Neir0 2010-03-13 18:21:05

+0

對不起。我的評論是丟失格式。 我的意思是http://img708.imageshack.us/img708/2383/screengw.png – Neir0 2010-03-13 18:25:42

+0

Neir0 - 你試圖得到DockPanel設計的確切效果。您可以使用更加靈活的Grid來做同樣的事情,但是如果您需要添加或刪除項目,則需要更多的XAML並需要大量Row/Column/RowSpan/ColumnSpan值的維護。 – 2010-03-14 18:16:12

3

試試這個:

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

只是使按鈕所需的寬度和文本框會填補其餘的。


感謝您的收穫;以上糾正以妥善處理右邊的保證金。但是,這樣做會要求您在按鈕寬度更改時更新邊距。如果您計劃經常更改間距,則兩列是更好的解決方案。如果網格中有多個控件並且不想創建嵌套網格來處理這種分割,則使用邊距更清晰。

+0

但在這種情況下,按鈕已結束文本框。 在這裏,你可以看到截圖http://img214.imageshack.us/img214/918/screeneb.png – Neir0 2010-03-13 18:15:19

+0

這是一種我敢打賭的技術,是學習如何在沒有表格的情況下做CSS佈局。 – 2010-03-14 08:34:34

+0

這也是Blend如果在網格中刪除和調整控件大小時會「猜測」的代碼類型。 – 2010-03-14 14:16:33

2

最簡單的方法是使用,而不是一個網格一個DockPanel中(用於LastChildFill默認是事實,但我還添加了在這裏爲清楚起見):

<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> 
相關問題