如何在 WPF 中将宽度设置为 100%
有没有办法告诉 WPF 中的组件占用 100% 的可用空间?
就像
width: 100%;
在 CSS 中
一样,我有这个 XAML,但我不知道如何强制 Grid 采用 100% 宽度。
<ListBox Name="lstConnections">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="LightPink">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
结果看起来像
替代文字 http://foto.darth.cz/pictures/wpf_width.jpg
我把它变成了粉红色所以很明显它占用了多少空间。 我需要将粉色网格设置为 100% 宽度。
Is there any way how to tell component in WPF to take 100% of available space?
Like
width: 100%;
in CSS
I've got this XAML, and I don't know how to force Grid to take 100% width.
<ListBox Name="lstConnections">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="LightPink">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"></TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Result looks like
alt text http://foto.darth.cz/pictures/wpf_width.jpg
I made it pink so it's obvious how much space does it take. I need to make the pink grid 100% width.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它是
Grid
的容器,它决定了它的宽度。 在本例中,这是一个ListBoxItem
,默认情况下左对齐。 您可以将其设置为拉伸,如下所示:It is the container of the
Grid
that is imposing on its width. In this case, that's aListBoxItem
, which is left-aligned by default. You can set it to stretch as follows:您可以使用
HorizontalContentAlignment="Stretch"
,如下所示:You could use
HorizontalContentAlignment="Stretch"
as follows:对我来说,在具有 2 列和 2 行的
Grid
内使用组件时,使用Grid.ColumnSpan="2" Grid.RowSpan="2"
,使其跨越列:What worked for me, with a component inside a
Grid
with 2 columns and 2 rows, was to useGrid.ColumnSpan="2" Grid.RowSpan="2"
, to make it span across the columns: