如何设置宽度为100% 的 WPF

有没有办法告诉 WPF中的组件占用100% 的可用空间?

喜欢

width: 100%;

在 CSS 中

我有这个 XAML,我不知道如何强制网格采取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% 的宽度。

145320 次浏览

Grid的容器决定了它的宽度。在本例中,这是一个 ListBoxItem,默认情况下它是左对齐的。你可以设置如下:

<ListBox>
<!-- other XAML omitted, you just need to add the following bit -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>

你可以按以下方式使用 HorizontalContentAlignment="Stretch":

<ListBox HorizontalContentAlignment="Stretch"/>