0
votes

I am trying to get the text of a label to update on the front of end of my app. At the moment Im using Message Centre to send a notification up to the view model and increment a number that should update on the label in the view. Im using Xamarin Forms and PCL. I can get the number to log out in the debug so I know the message centre is working. But its not updating the view.

the relevant Xaml:

    <Label Text="{Binding counter}"

           Grid.Row="0"/>

The code behind:

 public partial class DriverDashboardView : ContentPage
{
    private DriverDashboardViewModel driverdashboardviewmodel;

    public DriverDashboardView()
    {

        InitializeComponent();

        this.Title = "Driver's Dashboard";
        BindingContext = driverdashboardviewmodel = new DriverDashboardViewModel();
        dataList.ItemTapped += DataList_ItemTapped;


    }

    private void DataList_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        DisplayAlert("Route Information","Various Data","OK");
    }

    protected async override void OnAppearing()
    {
        base.OnAppearing();
        await driverdashboardviewmodel.GetLabelInfo();
    }

}

The View Model:

 public class DriverDashboardViewModel:BaseViewModel,INotifyPropertyChanged
{

   private int messageCounter { get; set; }
   public string counter { get { return messageCounter.ToString(); }
                        set {
                            if (Equals(value, messageCounter)) return;
                            messageCounter = Convert.ToInt32(value);
                            OnPropertyChanged(nameof(counter));

                             } }


    public DriverDashboardViewModel()
    {

        MessagingCenter.Subscribe<App>((App)Application.Current, "Increase", (variable) => {

            messageCounter++;
        });

    }



    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
    }
}

And the relevant section that implements the message centre:

Foregroundmessages.cs:

MessagingCenter.Send((App)Xamarin.Forms.Application.Current, "Increase");

As stated the messaging centre works fine. It gets as far as the view model but doesnt update the counter variable to the view. I have tried setting the counter as an int and a string hence the conversion in the get and set. I also tried observable collection but that seemed redundant because its a single variable not a collection or list.

Any ideas?

1

1 Answers

2
votes

your code is updating the private messageCounter property, not the public counter property that you are binding to. Updating messageCounter does not cause PropertyChanged to fire.

MessagingCenter.Subscribe<App>((App)Application.Current, "Increase", (variable) => {
  messageCounter++;
});