XAML 如何计算AdaptativeGridView的列数

relj7zay  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(118)

当列数改变时,我需要在两个项目之间应用一个水平分隔线。因此,有必要在SizeChanged事件中获取此UWP AdaptativeGridView的列数。
AdaptiveGridView有一个“CalculateColumns”方法,但无法访问。
我尝试使用下面的代码进行计算,但没有达到预期效果:

var twoColumns = Math.Abs(AppWebsiteGridView.DesiredWidth - (AppWebsiteGridView.ActualWidth / 2));

        var oneColumn = Math.Abs(AppWebsiteGridView.ActualWidth - AppWebsiteGridView.DesiredWidth);

        var threeColumns = Math.Abs(AppWebsiteGridView.DesiredWidth - (AppWebsiteGridView.ActualWidth / 3));

        var numberOfItems = AppWebsiteGridView.Items.Count;

        if (AppWebsiteGridView.Items[numberOfItems - 1] is SignInModel lastItem && AppWebsiteGridView.Items[numberOfItems - 2] is SignInModel lastButOneItem
            && AppWebsiteGridView.Items[numberOfItems - 3] is SignInModel lastButTwoItem)
        {
            if (threeColumns < twoColumns)
            {
                lastItem.IsEndLine = false;
                lastButOneItem.IsEndLine = false;
                lastButTwoItem.IsEndLine = false;
            }

            else if (twoColumns < oneColumn)
            {
                lastItem.IsEndLine = false;
                lastButOneItem.IsEndLine = false;
                lastButTwoItem.IsEndLine = true;
            }

            else
            {
                lastItem.IsEndLine = false;
                lastButOneItem.IsEndLine = true;
                lastButTwoItem.IsEndLine = true;
            }
qgzx9mmu

qgzx9mmu1#

根据AdaptiveGridView的源代码如下:https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/63cbb4a51bdef59083ccfc86bbcba41f966d0027/Microsoft.Toolkit.Uwp.UI.Controls.Primitives/AdaptiveGridView/AdaptiveGridView.Properties.cs#L152
CalculateColumns方法根据containerWidthitemWidth计算列。itemWidth参数是DesiredWidthcontainerWidth参数是AdaptiveGridView的实际宽度。因此,您只需在自己的代码隐藏中使用该方法:

private static int CalculateColumns(double containerWidth, double itemWidth)
    {
        var columns = (int)Math.Round(containerWidth / itemWidth);
        if (columns == 0)
        {
            columns = 1;
        }

        return columns;
    }

相关问题