C# 如何在登录页面上实现ICommand
我是MVVM的新手,最近我发现按钮也可以绑定到类中的函数 因此,我所做的基本上是使用Linq验证用户名和密码,在代码背后使用click事件,如下所示:C# 如何在登录页面上实现ICommand,c#,wpf,mvvm,C#,Wpf,Mvvm,我是MVVM的新手,最近我发现按钮也可以绑定到类中的函数 因此,我所做的基本上是使用Linq验证用户名和密码,在代码背后使用click事件,如下所示: private void Login_Click(object sender, RoutedEventArgs e) { var user = from u in MyDBDataSet.logins where u.username == usernameTextBox.Text
private void Login_Click(object sender, RoutedEventArgs e)
{
var user = from u in MyDBDataSet.logins
where u.username == usernameTextBox.Text
&& u.password == passwordPasswordBox.Password
select u;
if (user.Any())
{
MessageBox.Show("Success, Credentials Found");
}
else
{
MessageBox.Show("Error, Nothing Found");
}
}
为了让我使用MVVM模式,我最终不得不做这样的事情,对吗
<!-- Create the binding in the xaml />
<Button Content="Login" Command="{Binding login}"/>
在视图模型中,创建要将按钮绑定到的属性
private ICommand _login;
public ICommand login
{
get;
set;
}
这就是我对它的了解非常有限的地方。环顾四周,我了解到我需要告诉它在什么条件下可以执行,否则当应用程序运行时按钮会变灰,我还应该告诉它执行时该做什么
但目前这正是让我失望的地方。如何连接该方法以将用户登录到ICommand属性?您需要创建/获取一个名为
DelegateCommand的通用MVVM模式基类。基本上,这个类实现了ICommand
允许您为ICommand
接口中的Execute()
和CanExecute()
方法指定委托
PRISM库包含它的一个实现,它也是
private ICommand _login;
public ICommand login
{
get;
set;
}