En la siguiente clase de ejemplo, se crea un objeto con una coleccion observable y se llena por defecto, asignando a cada clase de sus elementos un evento.
Sin embargo, al hacer un cambio sobre los elementos, estos no saben cual es el listener del evento y no lo disparan. A que puede deberse?
class Program
{
static void Main(string[] args)
{
RestriccionVM restriccionVM = new RestriccionVM();
Console.WriteLine("inicia");
Console.WriteLine("deberia mostrar 1");
restriccionVM.ListaSistema[0].Chequeado = true;
Console.WriteLine("deberia haberse visto 1");
Console.WriteLine("deberia mostrar 1,2");
restriccionVM.ListaSistema[1].Chequeado = true;
Console.WriteLine("deberia haberse visto 1,2");
Console.ReadKey();
}
public class RestriccionVM
{
public ObservableCollection<ObjetosParaListview> ListaSistema
{
get;
set;
}
#region contructores
public RestriccionVM()
{
ObjetosParaListview ObjetoTemporal;
ListaSistema = new ObservableCollection<ObjetosParaListview>();
ObjetoTemporal = new ObjetosParaListview { Chequeado = false, Texto = "1" };
ObjetoTemporal.CambioUnCheck += HacerCambioDeCheck();
ListaSistema.Add(ObjetoTemporal);
ObjetoTemporal = new ObjetosParaListview { Chequeado = false, Texto = "2" };
ObjetoTemporal.CambioUnCheck += HacerCambioDeCheck();
ListaSistema.Add(ObjetoTemporal);
ObjetoTemporal = new ObjetosParaListview { Chequeado = false, Texto = "3" };
ObjetoTemporal.CambioUnCheck += HacerCambioDeCheck();
ListaSistema.Add(ObjetoTemporal);
}
#endregion
public Action HacerCambioDeCheck()
{
Console.WriteLine("entro al evento");
List<string> lista = new List<string>();
foreach (ObjetosParaListview o in ListaSistema)
{
if (o.Chequeado)
{
lista.Add(o.Texto);
}
}
Console.WriteLine(string.Join(",", lista));
return null;
}
}
public class ObjetosParaListview
{
public event Action CambioUnCheck;
private bool _Chequeado;
public bool Chequeado
{
get
{
return _Chequeado;
}
set
{
if (!_Chequeado.Equals(value))
{
_Chequeado = value;
CambioUnCheck?.Invoke();
Console.WriteLine("cambio");
}
}
}
private string _Texto;
public string Texto
{
get
{
return _Texto;
}
set
{
_Texto = value;
}
}
}
}