根据UWP中的屏幕尺寸的Gridview项目动态宽度 [英] Gridview Item dynamic width according to Screen Size in UWP

查看:124
本文介绍了根据UWP中的屏幕尺寸的Gridview项目动态宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个GridView,它通过数据绑定获取数据.我下一步要做的是根据屏幕大小使GridView项目的宽度动态变化(就像他们在Windows 10新闻,体育应用程序等中所做的一样.)到目前为止,我已经做到了使用视觉状态管理器,通过将水平对齐方式设置为拉伸,可以成功地将最小窗口宽度设置为0,但是对于其他更宽的窗口尺寸,我无法继续执行此操作.

I have created a GridView which gets data through data binding. What I want to do next is make the GridView item width dynamic according to the Screen Size (Like the ones they have done in the Windows 10 news, sports app, etc.) So far I have done it successfully for minimum window width 0 using visual state manager by setting the horizontal alignment to stretch, but I am not being able to continue this for other wider window sizes.

任何帮助您解决此问题的帮助.

Any kind of help for sorting this out will be appreciated.

推荐答案

如果希望项目拉伸以填充水平空间 并能够指定每行要多少个项目,则您必须在GridView的SizeChanged事件中手动设置ItemsWrapGrid的ItemWidth.

If you want the items to stretch to fill the horizontal space and be able to specify how many items per row you want, then you'll have to set the ItemWidth of the ItemsWrapGrid manually within the GridView's SizeChanged event.

这是一个例子:

<GridView x:Name="gridView" SizeChanged="onGridViewSizeChanged">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Grid Background="GreenYellow" BorderBrush="Black" BorderThickness="2">
                <TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="40"/>
            </Grid>
        </DataTemplate>
    </GridView.ItemTemplate>

    <GridView.ItemContainerStyle>
        <Style TargetType="GridViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
            <Setter Property="Margin" Value="0"/>
        </Style>
    </GridView.ItemContainerStyle>

    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <x:String>1</x:String>
    <x:String>2</x:String>
    <x:String>3</x:String>
    <x:String>4</x:String>
    <x:String>5</x:String>
    <x:String>6</x:String>
    <x:String>7</x:String>
    <x:String>8</x:String>
</GridView>

private void onGridViewSizeChanged(object sender, SizeChangedEventArgs e)
{
    // Here I'm calculating the number of columns I want based on
    // the width of the page
    var columns = Math.Ceiling(ActualWidth / 300);
    ((ItemsWrapGrid)gridView.ItemsPanelRoot).ItemWidth = e.NewSize.Width / columns;
}

您可能也可以将其捆绑到Behavior或附加的属性中.

You could probably bundle this into a Behavior or attached property too.

这篇关于根据UWP中的屏幕尺寸的Gridview项目动态宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆