Search code examples
c#xamluser-interfaceuwpgrid-layout

How to Count The Number Of Columns Of An AdaptativeGridView


I need to apply a horizontal separator line bwteen items, when columns number change. So, it's necessary to get the number of columns of this UWP AdaptativeGridView, inside a SizeChanged event.

AdaptiveGridView have a "CalculateColumns" method, but it's not accessible.

I tried to calculate using the code below, but didn't worked as I expected:

        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;
            }

Solution

  • According to the source code of the AdaptiveGridView here: https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/63cbb4a51bdef59083ccfc86bbcba41f966d0027/Microsoft.Toolkit.Uwp.UI.Controls.Primitives/AdaptiveGridView/AdaptiveGridView.Properties.cs#L152

    The CalculateColumns method is calculating the columns based on containerWidth and itemWidth. The itemWidth parameter is the DesiredWidth and the containerWidth parameter is the actual width of the AdaptiveGridView. So what you need to do is just use the method in your own code-behind:

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