user1943020
user1943020

Reputation:

How can I change from using a static class to hold globals to using a Singleton pattern?

Right now my code looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
namespace City
{
    public static class MS 
    {

        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

        private static void NotifyStaticPropertyChanged(string propertyName)
        {
            if (StaticPropertyChanged != null)
                StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }

        private static int timerSeconds;
        public static int TimerSeconds
        {
            get { return timerSeconds; }
            set { timerSeconds = value; NotifyStaticPropertyChanged("TimerSeconds"); }
        }
    }
}

and this XAML

 <Label x:Name="timer" Text="{Binding Source={x:Static local:MS.TimerSeconds}}" />
        </Grid>

The code works but in a previous questions one of the posters said this:

I would strongly recomend you to not use static class to keep data and bind something to them. Stange things may happen - in your code you are calling event with null sender. Event if it's working right now, it may not work with future releases of Xamarin.Forms. At least use singleton pattern - it allows you to implement INotifyPropertyChanged interface

Can someone explain or show me a very short example of what is meant here. Should I for example create a class in the application start area and how could I change that to implement INotifyPropertyChanged?

Upvotes: 0

Views: 90

Answers (1)

Yuri S
Yuri S

Reputation: 5370

Here is what you can do. Implement below and if you need a singleton (I am not sure why as I don't know your design) you access it as "MSSingleton.Instance" but I would try to avoid even singleton and just create MS object when you need it.

    public class MSSingleton : INotifyPropertyChanged
    {
        //if you need singleton
        static MSSingleton _instance = null;
        public static MSSingleton Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new MSSingleton();
                return _instance;
            }

        }


        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private int timerSeconds;

        public event PropertyChangedEventHandler PropertyChanged;

        public int TimerSeconds
        {
            get { return timerSeconds; }
            set { timerSeconds = value; OnPropertyChanged("TimerSeconds"); }
        }
    }

Upvotes: 3

Related Questions