如何在 MVVM Xamarin Forms 中将参数传递给 Singleton

How to pass a parameter to Singleton in MVVM Xamarin Forms

我想从另一个 ViewModel 添加一个元素到 ObservableCollection ...问题是,当通过单例生成该 ViewModel 的实例时,我收到构造函数接收参数的错误

There is no argument given that corresponds to the required formal parameter 'centroLegado' of 'GenerarRetiroCentroViewModel.GenerarRetiroCentroViewModel(CentroGeneracion)'

如何实现单例以便我可以从另一个 ViewModel 调用它?

我附上了具有 Observable 集合和构造函数的 ViewModel 的代码..

GenerarRetiroCentroViewModel.CS:

 #region Constructor
  public GenerarRetiroCentroViewModel(CentroGeneracion centroLegado)
  {
      instance = this;   

      ListaResiduosTemporales = new ObservableCollection<ResiduosTemporal>();

      centroSeleccionado = centroLegado;

 }    
 #endregion

 #region Singleton
  static GenerarRetiroCentroViewModel instance;

  public static  GenerarRetiroCentroViewModel GetInstance()
  {
      if (instance == null)
      {
          return new GenerarRetiroCentroViewModel();
      }
      return instance;
 }
 #endregion

我附上我如何 "wish" 从另一个 ViewModel (SelectResiduoViewModel.CS)

调用我的 ObservableCollection 的代码

SeleccionarResiduoViewModel.CS:

           var objeto = new ResiduosTemporal
            {
                IdResiduo = IdResiduo,
                NombreResiduo = NombreResiduo,
                IdEstimado = IdUnidad,
                NombreEstimado = NombreUnidad,
                IdContenedor = IdContenedor,
                NombreContenedor = NombreContenedor,

            };

            var generarRetiroCentroViewModel = GenerarRetiroCentroViewModel.GetInstance();

            generarRetiroViewModel.ListaResiduosTemporales.Add(objecto);

如何添加 Mode 对象来填充另一个 ViewModel 中的控件? SINGLETON 可以吗?我该怎么做?对我有什么帮助吗?

(其实我忘记回答了。抱歉¯\_(ツ)_/¯)

如我评论中所述,您只需正确填写参数即可。您期待 CentroGeneracion 但您没有传递任何参数。如果不需要,请创建第二个空构造函数。

此外,您永远不会分配实例 属性,这意味着如果您调用该函数,您将始终 return 一个新的单例实例。 应该是

public GenerarRetiroCentroViewModel GetInstance()
{
    if(instance == null){
        instance = new GenerarRetiroCentroViewModel();
    }

    return instance;
}

实际上,您甚至不需要函数。

public GenerarRetiroCentroViewModel Instance
{
    get
    {
        if(instance == null){
            instance = new GenerarRetiroCentroViewModel();
        }

        return instance;
    }
}

注意:这不是线程安全的。 如果你想让它线程安全,你可以使用 Lazy (.NET 4+).

public sealed class SingletonClass
{
    private static readonly Lazy<SingletonClass> _lazy =  new Lazy<SingletonClass>(() => new SingletonClass());

    public static SingletonClass Instance 
    {
        get
        {
            return _lazy.Value;
        }
    }

}

它基本上是在有人第一次尝试访问时创建一个单例 属性。