c# – Label won't update even though the values are passed-ThrowExceptions

Exception or error:

I am having some trouble with updating a label. In an Xaml.cs, I want to pass a value to another page, but not switching pages or so. Here is the code that I used:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using EscapeHaarlem.Models;
using EscapeHaarlem.Views;
using EscapeHaarlem.ViewModels;
using EscapeHaarlem.Services;

namespace EscapeHaarlem.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ItemsPage : ContentPage
{
    ItemsViewModel viewModel;
    AboutPage aboutPage ;
    int Cost;
    public ItemsPage()
    {
        InitializeComponent();
        BindingContext = viewModel = new ItemsViewModel();
        aboutPage = new AboutPage();
    }

    async void AddItem_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushModalAsync(new NavigationPage(new NewItemPage()));
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        if (viewModel.Items.Count == 0)
            viewModel.LoadItemsCommand.Execute(null);
    }

    private async void FlowListView_FlowItemTapped(object sender, ItemTappedEventArgs e)
    {
        var item = e.Item as Item;
        if (item == null)
            return;

        bool answer = await DisplayAlert(item.Text, item.Description, "Yes", "No");

        if (answer == true)
        {
            Cost = Cost + item.Cost;
            aboutPage.UpdatePusnihLabel(Cost);
            await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item)));
        }
        else
        {
            return;
        }
        //ItemsPage.ListView.Item = null;
    }
}
}

Where the AboutPage is the page that needs the new value. After the display alert and the user pressed Ok, there should be a cost sent to the AboutPage. The value of Cost comes from a MockDataStore as example:

new Item { Id = Guid.NewGuid().ToString(), Text = "Item 1", Description="This is an item description.", Cost = 1},

When I read the values with breakpoints in debugging mode all values are passed right. But when I want to display it in the AboutPage it won’t change. This is the code from the Xaml.cs of the AboutPage:

    public void UpdatePusnihLabel(int Count)
    {
        lblCounter.Text = Count.ToString();
    }

Even here my values are right. But even if I try lblCounter.Text = "Hello world"; it won’t update the label.

This is the Xaml of the AboutPage label:

<StackLayout Grid.Column="2" VerticalOptions="Center">
    <Label x:Name="lblCounter" HorizontalTextAlignment="Center" Rotation="270" FontSize="40" HorizontalOptions="Start" ></Label>
</StackLayout>

Hope someone can tell me why my label won’t update / show any text at all.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *