为什么 Grid 或 StackPanel 没有拉伸到容器控件的整个宽度?

Why isn't a Grid or a StackPanel stretched to full width of container control?

我尝试在 GridView 控件中显示一些文本。

每个 DataTemplate 都包含一个带有一些文本内容的 Grid

每个 Grid 应该在 ItemControl 内伸展到全宽,但它没有:


为什么?

无论我给 Grid.HorizontalAlignment 赋什么值,它都不会改变任何东西。

这是我的源代码:

<Page
  x:Class="BindingTest1.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:models="using:BindingTest1.Models"
  xmlns:me="using:BindingTest1"
  mc:Ignorable="d">
  <Page.Background>
    <ImageBrush ImageSource="Assets/engine-blades.jpg" Stretch="UniformToFill"/>
  </Page.Background>

  <Page.Resources>
    <Style x:Key="HeaderTextBlock" TargetType="TextBlock" BasedOn="{StaticResource TitleTextBlockStyle}">
      <Setter Property="Foreground" Value="Crimson" />
    </Style>
    <Style x:Key="SubHeaderTextBlock" TargetType="TextBlock" BasedOn="{StaticResource SubtitleTextBlockStyle}">
      <Setter Property="Foreground" Value="DarkOrange" />
    </Style>
  </Page.Resources>

  <StackPanel>
    <GridView ItemsSource="{x:Bind CdList}">
      <!--<GridView.ItemsPanel>
        <ItemsPanelTemplate>
          <me:MyDynamicSizePanel/>
        </ItemsPanelTemplate>
      </GridView.ItemsPanel>-->

      <GridView.ItemTemplate>
        <DataTemplate x:DataType="models:CD">

          <Grid BorderThickness="2" BorderBrush="SaddleBrown" HorizontalAlignment="Stretch">
            <Grid.RowDefinitions>
              <RowDefinition />
              <RowDefinition />
              <RowDefinition />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Style="{StaticResource HeaderTextBlock}" Text="{x:Bind Artist}"></TextBlock>
            <TextBlock Grid.Row="1" Style="{StaticResource SubHeaderTextBlock}" Text="{x:Bind Name}"></TextBlock>
            <TextBlock Grid.Row="2" Style="{StaticResource SubHeaderTextBlock}">
              <Run>Test</Run>
              <LineBreak/>
              <Run>Test</Run>
            </TextBlock>
          </Grid>

        </DataTemplate>
      </GridView.ItemTemplate>
    </GridView>
  </StackPanel>
</Page>

您可以通过配置GridView.ItemContainerStyle来实现您的目标:

<GridView ...>
    <GridView.ItemContainerStyle>
        <Style TargetType="GridViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Stretch" />
        </Style>
    </GridView.ItemContainerStyle>
    
    <!-- other code -->
</GridView>