如何水平拉伸GridViewItem?试图在HorizontalContentAlignment
中设置属性ItemContainerStyle
或样式属性。这无济于事。
这是一个代码:
<GridView ItemsSource="{x:Bind Banks}" SelectionMode="None" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</GridView.ItemContainerStyle>
<GridView.ItemTemplate>
<DataTemplate x:DataType="model:Bank">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Grid.Column="0" />
<GridView ItemsSource="{x:Bind Departments}" Grid.Row="1" HorizontalContentAlignment="Stretch" IsItemClickEnabled="True" VerticalContentAlignment="Stretch">
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</GridView.ItemContainerStyle>
<GridView.ItemTemplate>
<DataTemplate x:DataType="model:Department">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="40" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Grid.Column="0" />
<TextBlock Text="{Binding Address}" Grid.Column="0" Grid.Row="1" />
<TextBlock Text="{Binding USD.Date}" Grid.Column="1" Grid.RowSpan="2"/>
<TextBlock Text="{Binding USD.Sell}" Grid.Column="2" />
<TextBlock Text="{Binding USD.Buy}" Grid.Column="2" Grid.Row="1"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
最佳答案
默认情况下,GridView
使用ItemsWrapGrid
作为面板来放置和排列GridViewItem
,您可以从Live Visual Tree中找到它:
尽管已将HorizontalContentAlignment
的HorizontalAlignment
或Stretch
设置为GridViewItem
,但是GridViewItem
的大小受ItemsWrapGrid
限制。
ItemsWrapGrid
在显示多个项目的ItemsControl
中,从左到右或从上到下依次放置子元素。当元素超出容器边缘时,元素将位于下一行或下一列。
因此,在ItemsWrapGrid
中,项目不会被拉伸。
如果要水平拉伸GridViewItem
,我们可以使用ItemsStackPanel
代替ItemsWrapGrid
,如下所示:
在Resources
中,添加带有ItemsPanelTemplate
的ItemsStackPanel
:
<Page.Resources>
<ItemsPanelTemplate x:Key="MyItemsPanelTemplate">
<ItemsStackPanel />
</ItemsPanelTemplate>
</Page.Resources>
然后在
GridView
中使用此模板:<GridView HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
ItemsPanel="{StaticResource MyItemsPanelTemplate}"
ItemsSource="{x:Bind Banks}"
SelectionMode="None">
...
<GridView Grid.Row="1"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
IsItemClickEnabled="True"
ItemsPanel="{StaticResource MyItemsPanelTemplate}"
ItemsSource="{x:Bind Departments}">
...
</GridView>
...
</GridView>
或者我们可以使用
ListView
代替GridView
,因为ListView
的默认ItemsPanel
是ItemsStackPanel
。