我有一段XAML代码:
<Grid>
<WrapPanel>
<TextBox ></TextBox>
<Button Content="GetIt" />
</WrapPanel>
</Grid>
我该如何获得textBox的所有可用空间?
我想要做类似于这样的事情:
|[____________________][获取]|
<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 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>