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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/787436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:17:33  来源:igfitidea点击:

How to set width to 100% in WPF

wpfwidthautosize

提问by Jakub Arnold

Is there any way how to tell component in WPFto take 100% of available space?

有什么方法可以告诉WPF 中的组件占用 100% 的可用空间吗?

Like

喜欢

width: 100%;  

in CSS

在 CSS 中

I've got this XAML, and I don't know how to force Grid to take 100% width.

我有这个 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>

Result looks like

结果看起来像

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

替代文字 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.

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

回答by Kent Boogaart

It is the container of the Gridthat is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

它是 的容器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>

回答by Giovanny Farto M.

You could use HorizontalContentAlignment="Stretch"as follows:

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

<ListBox HorizontalContentAlignment="Stretch"/>