【发布时间】:2012-01-19 19:10:30
【问题描述】:
我正在学习使用 Prism 的 DelgateCommand....
在我的 UI 中,我有我的用户名文本框和密码框:
<TextBox Name="_UserNameTextBox" Text="{Binding UserName, Mode=TwoWay}" />
<PasswordBox Name="_PasswordBox"></PasswordBox>
还有我的登录按钮:
<Button Name="button1" Command="{Binding LoginCommand, Mode=TwoWay}" CommandTarget="{Binding ElementName=_UserNameTextBox, Path=Text}">Login</Button>
然后我的 ViewModel 我有:
string _UserName = string.Empty;
public string UserName
{
get
{
return _UserName;
}
set
{
if (value != _UserName)
{
_UserName = value;
RaisePropertyChanged("UserName");
}
}
}
//For reference the password
PasswordBox _PasswordBox { get; set; }
public DelegateCommand<string> LoginCommand { get; set; }
public LoginViewModel(PasswordBox passwordBox)
{
_PasswordBox = passwordBox;
LoginCommand = new DelegateCommand<string>(
(
//Execute
(str) =>
{
Login(_PasswordBox.Password);
}
),
//CanExecute Delgate
(usr) =>
{
if (string.IsNullOrEmpty(usr) || string.IsNullOrEmpty(_PasswordBox.Password))
return false;
return true;
}
);
}
我可以看到我的用户名已正确绑定,并且我确实将我的 PasswordBox 作为 ViewModel 构造函数中的引用传递了。当我执行应用程序时,按钮被禁用,所以我知道它已绑定到命令。
但是在我在 UserName 和 PasswordBox 中键入内容后,我从未看到我编写的 CanExecute 委托被检查...并且从未启用...
那么我做错了什么?
编辑:
=====
所以最终结果是……这个?
string _UserName = string.Empty;
public string UserName
{
get
{
return _UserName;
}
set
{
if (value != _UserName)
{
_UserName = value;
RaisePropertyChanged("UserName");
LoginCommand.RaiseCanExecuteChanged();
}
}
}
//For reference the password
PasswordBox _PasswordBox { get; set; }
public DelegateCommand<string> LoginCommand { get; set; }
public LoginViewModel(PasswordBox passwordBox)
{
_PasswordBox = passwordBox;
_PasswordBox.PasswordChanged += delegate(object sender, System.Windows.RoutedEventArgs e)
{
LoginCommand.RaiseCanExecuteChanged();
};
LoginCommand = new DelegateCommand<string>(
(
(str) =>
{
Login(_PasswordBox.Password);
}
),
(usr) =>
{
if (string.IsNullOrEmpty(usr) || string.IsNullOrEmpty(_PasswordBox.Password))
return false;
return true;
}
);
}
【问题讨论】:
-
CanExecute 委托在哪里.. 你必须设置 button.Enabled = true;你在哪里做那个..??
-
嗯? DelgateCommand
中的第二个参数是 Func 我正在传递一个 Lambada 表达式,仅当 UserName 不为 null 或为空,Password 不为 null 或为空时才返回 true。还是我做错了? -
您不应该在那里引用 PasswordBox,正如 Jon 所说,将密码也设为属性。
-
@H.B.我试图将其设为属性,但 Binding PasswordBox 存在问题...“无法在“PasswordBox”类型的“Password”属性上设置“Binding”。“Binding”只能在 DependencyProperty 上设置依赖对象。”
-
@KingChan:好吧,祝你好运,我很确定以前有人问过这个问题。另外,问乔恩,他毕竟建议过......