Share via

Updating content between tabs binded by Preference

mrizoiwe98 66 Reputation points
2021-03-29T16:40:52.617+00:00

I am using a tabbed app and I have a button on one tab, when the user clicks then it increments a Preference and I want to update its value on another tab. I tried to experiment with MVVM but I couldnt figure it out.

  public partial class Page1View: ContentPage
    {
        public Page1View()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            Preferences.Set("Total", Preferences.Get("Total", 0)+1);
        }
    }


public class Page2ViewModule : INotifyPropertyChanged
    {
        public int Total
        {
            get => Preferences.Get(nameof(Total), 0);
            set
            {
                if (Preferences.Get(nameof(Total),0) == value)
                    return;
                Preferences.Set(nameof(Total), value);
                OnPropertyChanged(nameof(Total));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var changed = PropertyChanged;
            if (changed != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
Developer technologies | .NET | Xamarin
0 comments No comments

Answer accepted by question author

Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,756 Reputation points
2021-03-30T02:31:39.303+00:00

Hello,

Welcome to Microsoft Q&A!

@mrizoiwe98

You update the value with Preferences , but this will not trigger the change notify of Property Total in Page2ViewModule.

Total does not update , so the Label(or something else) does not update .

We should take a way to tell Total it should be changed after button clicking .

Here I suggest you use Messaging Center , I've mentioned it in this thread .

Here we just move the messaging center into Set method of the property .

   set  
   {  
        MessagingCenter.Subscribe<object>(this, "Hi", (o) => {                
                  OnPropertyChanged(nameof(Total));  
         });                          
   }  

If you have any question please let me know .


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.