Reputation: 969
I want to pass a method in the MainViewModel to a delegate variable in the LoginViewModel object like this:
public class ApplicationViewModel : INotifyPropertyChanged
{
private LoginViewModel loginViewModel;
public ApplicationViewModel()
{
loginViewModel = new LoginViewModel();
this.loginViewModel.Login += this.checkLoginData; //stays null..
CurrentPageViewModel = this.loginViewModel; //works fine
}
private void checkLoginData(string username, string password)
{
//validating data
}
}
But for some reason, the loginViewModel.Login is null...
And this Command in the LoginViewModel keeps firing this at start, and telling me that the Login == null, which is not what I expect because I initialize the delegate at the MainViewModel constructor.
I'm not a expert at MVVM/WPF, but I trying to work for it.
EDIT: extra information.
And loginViewModel.Login is a delegate variable like this:
class LoginViewModel : ObservableObject, IPageViewModel
{
public delegate void DelegateLogin(string username, string password);
private DelegateLogin _login;
public DelegateLogin Login
{
get { return this._login; }
set
{
/*
if(this._login != value)
{
this._login = value;
OnPropertyChanged("Login");
}*/
this._login = value;
OnPropertyChanged("Login");
}
}
public ICommand CheckLoginCommand
{
get
{
if (Login != null)
{
this.checkLoginCommand = new Command(p => { Login(this._username, this._password); });
}
else
{
System.Windows.MessageBox.Show("Login DELEGATE IS EMPTY!?!?!"); //keeps firing...
}
return this.checkLoginCommand;
}
}
}
Upvotes: 2
Views: 1016
Reputation: 102793
Try this:
public ICommand CheckLoginCommand
{
get
{
if (this.checkLoginCommand == null)
this.checkLoginCommand = new Command(p => {
if (Login != null)
Login(this._username, this._password);
else
System.Windows.MessageBox.Show("Login DELEGATE IS EMPTY!?!?!"); //keeps firing...
});
return this.checkLoginCommand;
}
}
This has the advantage of creating the command regardless of whether the Login
delegate set. Other things aside, hopefully Login
will be ready by the time the command gets invoked.
Upvotes: 2