Home > Back-end >  How to get Preferences value from another page without reloading the page in Xamarin
How to get Preferences value from another page without reloading the page in Xamarin

Time:09-17

I have

  1. Page1.xaml

    <Label x:Name="getPreferences" />
    <Button x:Name="one" Clicked="one_Clicked"/>
    
  2. Page1.xaml.cs

    public Page1()
    {
        string getpre = Preferences.Get("PreOne", "defaultpre");
        getPreferences.Text = getpre;
    }
    private async void one_Clicked(object sender, EventArgs e)
    {
       PopupNavigation.Instance.PushAsync(new Popup());
    }
    
  3. Popup.xaml (using Rg Popup)

    <popup:PopupPage
      ....
      <StackLayout x:Name="ss">
                     <Image Source="img"/>
                     <Label Text="Testtttt" />
                     <StackLayout.GestureRecognizers>
                         <TapGestureRecognizer Tapped="ss_Tapped" />
                     </StackLayout.GestureRecognizers>
                 </StackLayout>
    </popup:PopupPage>
    
  4. Popup.xaml.cs

    private void ss_Tapped(object sender, EventArgs e)
    {
       string setone = "01";
       Preferences.Set("PreOne", setone);
    }
    

How can I get the value of Preferences to assign to the Label getPreferences without me having to reload the page Page1. Please help. Thank you

CodePudding user response:

Try using ViewModels and bindings so that all these things happen automatically

CodePudding user response:

Preferences Essential package have no event for changing preferences , so you have to get your value every time you change it . i suggest you to create your own event in popup and fire it when your value changed

1.PopUp.xaml.cs

    public event EventHandler PreOneChanged; 
    private void ss_Tapped(object sender, EventArgs e)
    {
        string setone = "01";
        Preferences.Set("PreOne", setone);
        PreOneChanged?.Invoke(setone,EventArgs.Empty);
    }

2.Page1.xaml.cs

    public Page1()
    {
        Init();
    }

    private void Init()
    {
        string getpre = Preferences.Get("PreOne", "defaultpre");
        getPreferences.Text = getpre;
    }
    private async void one_Clicked(object sender, EventArgs e)
    {
        var popUp = new Popup();
        popUp.PreOneChanged  = (ss, ee) =>
        {
            Init();
        };
        PopupNavigation.Instance.PushAsync(popUp);

    }

Now when your value changed in PopUp your event call and in page will change that

  • Related