如何从使用静态类来保存全局变量更改为使用单例模式?



现在我的代码看起来像这样:

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"); }
}
}
}

和这个 XAML

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

代码有效,但在之前的问题中,其中一张海报是这样说的:

我强烈建议您不要使用静态类来保存数据和 将某些东西绑定到它们上。斯坦奇事情可能会发生 - 在你的代码中你 正在调用具有空发送方的事件。事件,如果它现在正在工作, 它可能不适用于 Xamarin.Forms 的未来版本。至少使用 单例模式 - 它允许您实现 INotifyPropertyChanged 接口

有人可以解释或给我看一个非常简短的例子来说明这里的意思。例如,我是否应该在应用程序启动区域中创建一个类,以及如何更改它以实现 INotifyPropertyChanged?

这是您可以做的。 在下面实现,如果您需要一个单例(我不确定为什么,因为我不知道您的设计(,您可以将其作为"MSSingleton.Instance"访问,但我会尽量避免单例,只在需要时创建 MS 对象。

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"); }
}
}

最新更新