Home > Software design >  Xamarin Timer crashes
Xamarin Timer crashes

Time:11-30

So I've done this in code:

public partial class Timer : ContentView , INotifyPropertyChanged
    {
        private int seconds = 30;
        
        private System.Timers.Timer timer;
        public Timer()
        {
            InitializeComponent();
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.AutoReset = true;
            timer.Elapsed  = new System.Timers.ElapsedEventHandler(OneSecondPassed);
            timer.Enabled = true;
        }
        private void OneSecondPassed(object source, System.Timers.ElapsedEventArgs e)
        {
            seconds--;
            Time = seconds.ToString();
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public string Time
        {
            get => seconds.ToString();
            set
            {
                Time = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this ,  new PropertyChangedEventArgs("Time"));
                }
                
            }   
        }
    }

and then bound my label's text to it in XAML:

 <Label  BindingContext ="{x:Reference this}"
              Text="{Binding Time}"/>

When I start the app, it crashes...I don't really understand how PropertyChanged works, just that INotifyPropertyChanged implements it.Also, when I declare PropertyChanged, it tells me that BindableObject.PropertyChanged already exists, use new in order to hide it.If you could explain how the interface and its event works, I'd be really thankful.

CodePudding user response:

your setter is creating an infinite loop.

set
{
   // this will call the setter again, infinitely
   Time = value;
   ...
}

you already have a private variable for seconds, you should use it here

public int Time
    {
        get => seconds;
        set
        {
            seconds = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this ,  new PropertyChangedEventArgs("Time"));
            }
            
        }   
    }

private void OneSecondPassed(object source, System.Timers.ElapsedEventArgs e)
{
   Time--;
}

CodePudding user response:

when I declare PropertyChanged, it tells me that BindableObject.PropertyChanged already exists

I see that Timer inherits from ContentView.

ContentView is a BindableObject, so it already implements everything used in binding, such as PropertyChanged. Delete your declaration of PropertyChanged.


OPTIONAL: You could also remove , INotifyPropertyChanged - ContentView does that for you. However it is harmless to leave it there.

  • Related