(Closest related question)RelayCommand闭合
我执行LogInRequest()
它调用LogInView.ShowDialog()
。该视图有一个叫做VerifyLogInCommand
的命令。执行命令后,它会以this.CloseAction()
完成,它似乎关闭了对话框。但是,在该视图的命令的CanExecute方法VerifyLogInCanExecute
中,我的断点在关闭对话框(不间断)后仍然被触发。我试过在调用ShowDialog后将视图设置为null,但没有改变。
为什么当窗口关闭/ null时Command/CanExecute仍然被评估?
LogInView.xaml.cs
public LogInOutView()
{
InitializeComponent();
// Data context
IModule existingVM = SessionViewModel.Instance.ModulesOpen.Single(mod => mod.ModuleName == "LogIn");
LogInViewModel livm = (LogInViewModel)existingVM;
this.DataContext = livm;
// Cancel Handler
livm.CloseAction = new Action(() => this.Close());
}
LogInViewModel.cs
public Action CloseAction { get; set; }
private RelayCommand verifyLogInCommand;
public RelayCommand VerifyLogInCommand
{
get
{
if (verifyLogInCommand == null)
{
verifyLogInCommand = new RelayCommand(
param => VerifyLogInExecute(),
param => VerifyLogInCanExecute);
}
return verifyLogInCommand;
}
}
public void VerifyLogInExecute()
{
// Validate Login
Employee employee = ValidateLogin(Password);
// Clear password field
ResetExecute();
// Return false if invalid login
if (employee == null)
{
Result = LogInOutDialogResults.Cancel;
ConfirmationView c = new ConfirmationView("Invalid Login!");
c.ShowDialog();
return;
}
// Set Result to LogIn status
Result = LogInOutDialogResults.LogIn;
// Set LastAuthorizedEmployee
SessionViewModel.Instance.LastAuthorizedEmployee = employee;
// Close View to go back where it was called
this.CloseAction();
}
public bool VerifyLogInCanExecute
{
get
{
// Password length restrictions
if (!CheckRequiredPasswordLength(Password)) { return false; }
return true;
}
}
public static LogInOutDialogResults LogInRequest()
{
// Show Login View
LogInOutDialogResults LogInOutResult = LogInOutDialogResults.Cancel;
LogInOutView LogInOutView = new LogInOutView()
{
Title = "Log In",
ShowInTaskbar = false,
Topmost = true,
ResizeMode = ResizeMode.NoResize,
Owner = SessionViewModel.Instance.ProfitPOSView
};
LogInOutView.ShowDialog();
LogInOutResult = ((LogInViewModel)LogInOutView.DataContext).Result;
// LogIn
if (LogInOutResult == LogInOutDialogResults.LogIn)
{
LogInOutView = null;
return LogInOutDialogResults.LogIn;
}
}
感谢您的好解释。我刚刚发现类似的解释设置命令为null时完成[这里也是](http://stackoverflow.com/a/6695530/1992193) –
我有同样的问题,但它发生在我的项目中,即使在我将命令设置为空,任何想法? – Chen
@Chen当你将你的命令清空时,你是在提升'PropertyChanged'吗?如果没有,绑定控件不知道该命令已被替换,并且将继续查询旧的。 –