我想从另一个ViewModel向ObservableCollection添加一个元素...问题是当通过单例生成该ViewModel的实例时,我得到构造函数接收参数的错误
没有任何参数对应于'GenerarRetiroCentroViewModel.GenerarRetiroCentroViewModel(CentroGeneracion)'所需的形式参数'centroLegado'
如何实现单例,以便我可以从另一个ViewModel调用它?
我附加了具有Observable Collection和构造函数的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
我附上了“希望”从其他ViewModel调用我的ObservableCollection的代码(SelectResiduoViewModel.CS)
选择ResidueViewModel.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
,但你没有传递任何论据。如果您不需要它,请创建第二个空构造函数。
此外,您永远不会分配实例属性,这意味着如果调用该函数,您将始终返回一个新的单例实例。它应该是
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;
}
}
}
它首次在有人试图访问该属性时创建一个Singleton。