如何在WPF中将宽度设置为100%

Jak*_*old 63 wpf autosize width

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

喜欢

width: 100%;  
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)

结果看起来像

替代文字http://foto.darth.cz/pictures/wpf_width.jpg

我把它做成了粉红色,这显然需要多少空间.我需要使粉红色网格100%宽度.

Ken*_*art 85

它是Grid宽容的容器.在这种情况下,这是a 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>
Run Code Online (Sandbox Code Playgroud)

  • 一个小注意事项 - 如果您尝试在Windows应用商店中执行此操作,则必须使用与上述相同的方法实际设置`Horizo​​ntalContentAlignment` (11认同)

Gio*_* M. 55

您可以使用HorizontalContentAlignment="Stretch"如下:

<ListBox HorizontalContentAlignment="Stretch"/>
Run Code Online (Sandbox Code Playgroud)