(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'嗎?如果沒有,綁定控件不知道該命令已被替換,並且將繼續查詢舊的。 –