微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从左侧菜单刷新页面

如何解决如何从左侧菜单刷新页面

Xamarin使用MVVM形式。以汉堡示例为例,具有左侧菜单

    //MainPage
    [XamlCompilation(XamlCompilationoptions.Compile)]
        public partial class MainPage : MasterDetailPage
        {
            int idOfNewPage;
            Dictionary<int,NavigationPage> MenuPages = new Dictionary<int,NavigationPage>();
            public MainPage()
            {
                InitializeComponent();
    
                MasterBehavior = MasterBehavior.Popover;
    
                MenuPages.Add((int)MenuItemType.Products,(NavigationPage)Detail);
            }
    
            public async Task NavigateFromMenu(int id)
            {
                if (!MenuPages.ContainsKey(id))
                {
                    switch (id)
                    {
                        case (int)MenuItemType.Products:
                            MenuPages.Add(id,new NavigationPage(new ProductPage()));
                            break;
                        case (int)MenuItemType.Shopping:
                            MenuPages.Add(id,new NavigationPage(new ShoppingPage()));
                            break;
                        case (int)MenuItemType.browse:
                            MenuPages.Add(id,new NavigationPage(new ItemsPage()));
                            break;
                        case (int)MenuItemType.About:
                            MenuPages.Add(id,new NavigationPage(new AboutPage()));
                            break;
                    }
    
                    idOfNewPage = id;
                }
    
                idOfNewPage = id;
    
                var newPage = MenuPages[id];
    
                if (newPage != null)
                {
                    Detail = newPage;
    
                    if (Device.RuntimePlatform == Device.Android)
                        await Task.Delay(100);
    
                    IsPresented = false;
                }
            }
    }
    
     [XamlCompilation(XamlCompilationoptions.Compile)]
        public partial class MenuPage : ContentPage
        {
            MainPage RootPage { get => Application.Current.MainPage as MainPage; }
            List<HomeMenuItem> menuItems;
        
            public MenuPage()
            {
                InitializeComponent();
    
                menuItems = new List<HomeMenuItem>
                {
                    new HomeMenuItem {Id = MenuItemType.Products,Title="Products",Icon =  "back_nav.png",Name = "test" },new HomeMenuItem {Id = MenuItemType.ShoppingCart,Title="Shopping Cart",Icon =  "back_nav.png"},new HomeMenuItem {Id = MenuItemType.browse,Title="browse",new HomeMenuItem {Id = MenuItemType.About,Title="About",Icon =  "back_nav.png"}
                };
    
                ListViewMenu.ItemsSource = menuItems;
       
                ListViewMenu.ItemSelected += async (sender,e) =>
                {
                    if (e.SelectedItem == null)
                     return;
    
                    var id = (int)((HomeMenuItem)e.SelectedItem).Id;
                    var MenuBtnClicked = (string)((HomeMenuItem)e.SelectedItem).Title;
    
    
                    await RootPage.NavigateFromMenu(id);
    
                    ListViewMenu.SelectedItem = null;
                };
            }
}

因此,一切正常,我可以使用左侧的菜单页面上跳回第四位。 但是,问题出在shoppingPage上。

产品列表视图显示在产品页面上。(如下)如果用户更改了产品数量,则会调用WineQuantityChanged()。更新屏幕上的数量调用-UpdateShoppingCartItems()。将产品添加到DrinksToPurchaseList中。 现在,当用户单击购物车图标(添加为工具栏项目,而不是从菜单添加)时,代码调用ShoppingClicked(),其中将DrinksToPurchase列表填充到App.globalShoppingCartOC中 并加载购物车页面

        //ProductPage.cs
     public ProductPage()
            {
            
              PopulateQuantityPicker();
    
                InitializeComponent();
                
                  productPage_ViewModal = new ProductPageviewmodel();
                  
                   NoItemsInShoppingCart.Text = App.NoOfItemsInShoppingCartGlobalVar;
                   
                     BindingContext = productPage_ViewModal;
                     
                     }
                     
            
            
            
            private async void ShoppingClicked(object sender,EventArgs e)
            {
                 //global list storing up to date products and quantites
                App.globalShoppingCartOC = DrinksToPurchase;
                await RootPage.NavigateFromMenu(1);
            }
            
  void WineQuantityChanged(object sender,EventArgs e)
        {
            var picker = (Picker)sender;
            int newQuantity = picker.Selectedindex;
            string winePickerId = picker.Id.ToString();
            int oldQuantity = -1;
            int tempDiffOfValues = 0;
            var product = (ProductModel)picker.BindingContext;
//code to update quantity 

//update shopping cart items
                UpdateShoppingCartItems(product,newQuantity);
                NoItemsInShoppingCart.Text = quantityOfProducts.ToString();
                App.NoOfItemsInShoppingCartGlobalVar = quantityOfProducts.ToString();

           }
        }


        //update item in shopping cart with new quantity
        void UpdateShoppingCartItems(ProductModel product,int quantity)
        {

            if (!DrinksToPurchaseList.Contains(product))
            {
                product.Quantity = quantity;
                DrinksToPurchaseList.Add(product);
            }
            else
            {
                ProductModel result = DrinksToPurchaseList.Where(x => x.ProductId == product.ProductId).FirstOrDefault();

                if (result != null)
                {
                    //remove from list
                    if (quantity < 1)
                    {
                        DrinksToPurchaseList.Remove(result);
                    }
                    else // else update new quantity
                    {
                        result.Quantity = quantity;
                    }
                }
            }
        }
            
            
            //ProductPage.xaml
            
             <ToolbarItem x:Name="NumberOfItemsInShoppingCart" Priority="0" Order="Primary" Activated="ShoppingClicked"/>
            
             <StackLayout Grid.Row="2">
                <Button Text="Wine" Clicked="WineClicked" WidthRequest="100" HorizontalOptions="Start"/>
                <ListView ItemsSource="{Binding WineList}" x:Name="WineListView" IsVisible="False" HasUnevenRows="True" SeparatorVisibility="None" VerticalOptions="FillAndExpand" VerticalScrollBarVisibility="Always" HeightRequest="1500">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                               
                                <Grid x:Name="Wine" RowSpacing="25">
                                    <Grid.RowDeFinitions>
                                        <RowDeFinition Height="Auto"/>
                                        <RowDeFinition Height="*"/>
                                    </Grid.RowDeFinitions>
                                    <Grid.ColumnDeFinitions>
                                        <ColumnDeFinition Width="Auto"/>
                                        <ColumnDeFinition Width="*"/>
                                    </Grid.ColumnDeFinitions>
                                    <Label Grid.Column="0" Grid.Row="0" Text="{Binding ProductId}" VerticalOptions="End" IsVisible="False"/>
                                    <controls:CircleImage  Grid.Column="1"  Grid.Row="0" HeightRequest="60" HorizontalOptions="CenterandExpand" VerticalOptions="Center" Aspect="AspectFill" WidthRequest="66" Grid.RowSpan="2" Source="{Binding Image}"/>
                                    <Label Grid.Column="2" Grid.Row="0" Text="{Binding ProductName}" VerticalOptions="Start"/>
                                    <Label Grid.Column="2" Grid.Row="0"  Text="{Binding Description}" VerticalOptions="End"/>
                                    <Label Grid.Column="3" Grid.Row="0" VerticalOptions="Start" Text="{Binding Price,StringFormat='£{0:0.00}'}"/>
                                    <Picker Grid.Column="4" Grid.Row="0" SelectedindexChanged="WineQuantityChanged" Selectedindex="{Binding Quantity}">
                                        <Picker.Items>
                                            <x:String>0</x:String>
                                            <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>
                                        </Picker.Items>
                                    </Picker>
                                </Grid>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

从购物车页面用户还可以更改商品的数量调用QuantityChanged()->调用UpdateShoppingCartItems()并用ShoppingCartviewmodel.ShoppingCartList(包含新数量)重新填充App.globalShoppingCartOC。 例如说他们更改数量,然后返回到产品页面(从左侧菜单)。

(应该在ProductPage上调用OnAppearing())并重新加载VM?

    public ShoppingCartPage ()
            {
                InitializeComponent();
    
                if (App.globalShoppingCartOC != null)
                {
                    foreach (ProductModel Model in App.globalShoppingCartOC)
                    {
                        if (Model.Quantity > 0)
                        {
//populate LV with global shopping OC
                            Model.SubTotalForItem = Model.Quantity * Model.Price;
                            ShoppingCartviewmodel.ShoppingCartList.Add(Model);//ShoppingCartList is the ListView on xaml
                            TotalForAllItems += Model.SubTotalForItem;
                        }
                    }
                }
    
                this.BindingContext = this;
                BindingContext = ShoppingCartviewmodel;
            }
    
         void QuantityChanged(object sender,EventArgs e)
            {
    //updates correct quantity on screen and calls
    //UpdateShoppingCartItems()
    }
    
        //update item in shopping cart with new quantity
            void UpdateShoppingCartItems(ProductModel product,int quantity)
            {
                ProductModel result = ShoppingCartviewmodel.ShoppingCartList.ToList().Find(x => x.ProductId == product.ProductId);
    
                if (result != null)
                {
                    //remove from list
                    if (quantity < 1)
                    {
                        ShoppingCartviewmodel.ShoppingCartList.Remove(result);
                    }
                    else // else update new quantity
                    {
                        result.Quantity = quantity;
                    }
                }
    
                App.globalShoppingCartOC = ShoppingCartviewmodel.ShoppingCartList;
            }
    
        //xaml
          <StackLayout Grid.Row="0">
    
                <ListView ItemsSource="{Binding ShoppingCartList}" HasUnevenRows="True" SeparatorVisibility="None">
                    <ListView.Header>
                        <Button Text="Place Order" Clicked="OrderPlaced_BtnClicked"/>
                    </ListView.Header>
                    <ListView.Footer>
                        <Label x:Name="TotalForItems" HorizontalTextAlignment="End" VerticalTextAlignment="Start" Margin="20,20" FontAttributes="Bold"/>
                    </ListView.Footer>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
    
                                <Grid x:Name="ShoppingCartGrid" RowSpacing="25" ColumnSpacing="10">
                                    <Grid.RowDeFinitions>
                                        <RowDeFinition Height="Auto"/>
                                        <RowDeFinition Height="*"/>
                                    </Grid.RowDeFinitions>
                                    <Grid.ColumnDeFinitions>
                                        <ColumnDeFinition Width="Auto"/>
                                        <ColumnDeFinition Width="*"/>
                                    </Grid.ColumnDeFinitions>
    
                                    <Label Grid.Column="0" Text="{Binding Id}" VerticalOptions="End" IsVisible="False"/>
                                    <controls:CircleImage  Grid.Column="1"  Grid.Row="1" HeightRequest="60" HorizontalOptions="CenterandExpand" VerticalOptions="CenterandExpand" Aspect="AspectFill" WidthRequest="66" Grid.RowSpan="2" Source="{Binding Image}"/>
                                    <Label Grid.Column="2" Grid.Row="1" Text="{Binding ProductName}" VerticalOptions="End"/>
                                    <Label Grid.Column="2" Grid.Row="2" VerticalOptions="Start" Text="{Binding Description}"/>
                                    <Label Grid.Column="3" Grid.Row="2" VerticalOptions="Start" Text="{Binding Price,StringFormat='£{0:0.00}'}"/>
    
                                    <Picker Grid.Column="4" Grid.Row="2" VerticalOptions="Start" SelectedindexChanged="QuantityChanged" Selectedindex="{Binding Quantity}">
                                        <Picker.Items>
                                            <x:String>0</x:String>
                                            <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>
                                        </Picker.Items>
                                    </Picker>
    
                                </Grid>
                            </ViewCell>

现在,从这里我需要从productPage_ViewModal.WineList的'WineList'重新加载所有产品,并遍历App.globalShoppingCartOC,以更新所有新数量

问题是我可以逐步执行,并且OnAppearing可以执行此操作,但是重新加载页面时,它会显示原始数量,即从用户第一次从产品页面移至购物车页面的原始数量。 (因此,数量存储在DrinksToOrder中)

AMEND

更新了代码以将OnAppearing包含在ProductPage中

protected override void OnAppearing()
    {
        base.OnAppearing();
        
        if (App.globalShoppingCartOC != null)
        {
            if (App.globalShoppingCartOC.Count > 0)
            {
                 foreach(var item in App.globalShoppingCartOC)
                {
                    if(item.Genre == "Wine")
                    {
                        productPage_ViewModal.WineList.Where(x => x.ProductId == item.ProductId).FirstOrDefault().Quantity = item.Quantity;
                    }
                }

                 WineListView.ItemsSource = productPage_ViewModal.WineList;
                 
                  this.BindingContext = this.productPage_ViewModal;
                  
                            }
        }
    }

因此,我可以逐步查看productPage_ViewModal.WineList和WineListView.ItemsSource中的物品的正确数量

然后甚至再一次对bindingContext感到厌倦...但是从购物车页面返回后,页面仍加载原始的DrinksToPurchaseList

这是为什么?为什么我不能刷新大众汽车来更新?

解决方法

Create an event on master page,invoke event from master page in your case blog and consume that event on another page where you want to refresh data..
on master page what you've to do is..
declare event..
public delegate void refreshDelegate();
public static event  refreshDelegate refreshEvent;
__
now invoke this event,refreshEvent?.inovke();

now,on the page where you want to refresh data,at constructor access the declared event,masterpage.refreshEvent+=masterpage_refreshEvent;  
   private void masterpage_refreshEvent()
  { 
BindData();
}
       
now,bind the data in invoked event,it'll refresh your screen as expected.  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。