使用freshmvvm推送新页面时的null引用

时间:2018-02-28 13:48:19

标签: c# xamarin xamarin.forms freshmvvm

我从列表中以编程方式创建了一个网格。但是,我也在使用freshmvvm,这给我带来了推新页面的麻烦。我注意到CoreMethods为空。这是我的班级。

using System;
using CashRegisterApp.ViewModels;
using Xamarin.Forms;

namespace CashRegisterApp.Pages
{
    //[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class InventoryPage : ContentPage
    {
        public InventoryPage()
        {
            InitializeComponent();
            BindingContext = new InventoryViewModel();
            CreateGrid();
        }

        /// <summary>
        /// Creates a grid specifically with the needed columns and rows for the list in the viewmodel
        /// </summary>
        private void CreateGrid()
        {
            //var grdInventory = new Grid();

            if (BindingContext is InventoryViewModel vm)
            {
                var buttonList = vm.Buttons;

                //determine the amount of rows needed to create the full grid of buttons
                var x = 5;
                decimal rowCount = buttonList.Count / x;
                var y = Math.Round(rowCount, MidpointRounding.AwayFromZero);
                if (y == 0)
                {
                    y = 1;
                }
                //declare the rows and the columns

                for (int i = 0; i != x; i++)
                {
                    grdInventory.ColumnDefinitions.Add(new ColumnDefinition{ Width = new GridLength(1, GridUnitType.Star)});
                }

                for (int i = 0; i != y; i++)
                {
                    grdInventory.RowDefinitions.Add(new RowDefinition{ Height = new GridLength(220)});
                }

                //fill in the grid using for loops atm cus it is the solution i know
                var count = 0;
                for (int i = 0; i != y && count != buttonList.Count; i++)
                {
                    for (int j = 0; j != x && count != buttonList.Count; j++)
                    {
                        grdInventory.Children.Add(buttonList[count], j, i);
                        count++;
                    }
                }
            }
        }    
    }
}

互联网并没有真正有用。然而,因为设置bindingcontext而在某人周围阅读时说。但如果我不这样做,我就无法使用viewmodel中的列表。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

根据FreshMvvm的约定配置机制,您需要从FreshBaseContentPage而不是ContentPage继承InventoryPage。

注意:您需要遵守该机制,即我们的页面名称(AKA视图)必须以&#34; Page&#34;并且我们的pageModels(AKA viewModel)的名称必须以&#34; PageModel&#34;结尾,例如: 页面-------&gt;我的页面 PageModel - &gt; MyPageModel

遵循该规则,您的BindingContext将自动正确设置。