【问题标题】:How to set width to 100% in WPF如何在 WPF 中将宽度设置为 100%
【发布时间】:2010-10-21 16:58:51
【问题描述】:

有没有办法告诉 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>

结果看起来像

alt text http://foto.darth.cz/pictures/wpf_width.jpg

我把它变成了粉红色,所以很明显它需要多少空间。我需要将粉色网格设为 100% 宽度。

【问题讨论】:

  • 链接已失效...
  • @MartiniBianco 对不起,这个问题已经 8 年了。我什至不记得图像中的内容,从那时起我也没有使用过 WPF。

标签: wpf width autosize


【解决方案1】:

强加于其宽度的是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>

【讨论】:

  • 一个小提示 - 如果您尝试在 Windows 商店应用程序中执行此操作,您必须使用与上述相同的方法实际设置 HorizontalContentAlignment
【解决方案2】:

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

<ListBox HorizontalContentAlignment="Stretch"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-19
    • 2014-05-26
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多