我正在用两个TextBox(用户名和密码)和一个Login按钮编写一个简单的登录UserControl。我希望仅在填写用户名和密码字段时才启用“登录”按钮。我正在使用Prism和MVVM。 LoginViewModel包含一个名为LoginCommand的属性,该属性绑定(bind)到Login按钮。我的ViewModel中有一个CanLoginExecute()方法,但仅在应用程序启动时才会触发,然后再也不会触发。因此,永远不会启用“登录”按钮。我想念什么?
这是我的xaml:
<TextBox x:Name="username"
Text="{Binding Path=Username, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<TextBox x:Name="password"
Text="{Binding Path=Password, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<Button Content="Login"
cmnd:Click.Command="{Binding LoginCommand}" />
这是我的ViewModel
class LoginViewModel : IDataErrorInfo, INotifyPropertyChanged
{
public LoginViewModel()
{
this.LoginCommand =
new DelegateCommand<object>(
this.LoginExecute, this.CanLoginExecute);
}
private Boolean CanLoginExecute(object dummyObject)
{
return (string.IsNullOrEmpty(Username) ||
string.IsNullOrEmpty(Password)) ? false : true;
}
private void LoginExecute(object dummyObject)
{
if (CheckCredentials(Username, Password))
{
....
}
}
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Username")
{
if (string.IsNullOrEmpty(Username))
result = "Please enter a username";
}
else if (columnName == "Password")
{
if (string.IsNullOrEmpty(Password))
result = "Please enter a password";
}
return result;
}
}
#endregion // IDataErrorInfo Members
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion // INotifyPropertyChanged Members
#region Properties
private String _username;
public String Username
{
get { return _username; }
set
{
if (value == _username)
return;
_username = value;
this.OnPropertyChanged("Username");
}
}
private String _password;
public String Password
{
get { return _password; }
set
{
if (value == _password)
return;
_password = value;
this.OnPropertyChanged("Password");
}
}
public ICommand LoginCommand { get; private set; }
#endregion // Properties
}
最佳答案
绑定(bind)控件很可能永远不会再询问CanExecute状态。每当您检测到更改命令的CanExecute状态的条件时,就需要在DelegateCommand上调用 RaiseCanExecuteChanged 方法。这向绑定(bind)的控件发出信号以更新CanExecute状态。
关于wpf - WPF-Prism CanExecute方法未调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2444927/