前几天初步看了一下WPF,按照网上说的一些方法,实现了WPF所谓的效果。但,今天我按照自己的思路设计了一个登陆界面,然后进行登陆验证,对WPF算是有进一步的理解,记录下来,以备后期查看。
首先,在WPF中,数据绑定很重要,也是WPF的核心。数据绑定和命令的绑定,需要后台来实现,主要是ViewModel来实现。
ViewModel中主要包含以下几项:
1、页面中所用到的参数,包括数据源和界面控件中的参数;这里的参数统一称为ViewModel的变量
2、ViewModel中需要定义一些命令参数来实现命令的绑定。数据的绑定统一绑定为ViewModel中的变量。
3、界面需要操作的变量属性,在ViewModel中封装时,要暴露给外面,在设置Set属性时,要进行特殊的处理。
4、在ViewModel中要实现界面按钮和其他需要的函数方法。
除了ViewModel外,还需要定义一个command类,继承于ICommand基类
下面是实现的核心代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication1
{
class LoginCommand:ICommand
{
private UserViewModelcs _userview;
public LoginCommand(UserViewModelcs userviewmodel)
{
this._userview = userviewmodel;
}
//ICommand 成员
public bool CanExecute(object parameter)
{
// throw new NotImplementedException();
return true;
}
public event EventHandler CanExecuteChanged
{
add { }
remove{}
}
public void Execute(object parameter)
{
//throw new NotImplementedException();
this._userview.login();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace WpfApplication1
{
class UserViewModelcs:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;//INotifyPropertyChanged 成员
//
//查询的数据
private Collection<User> _DataList = null;
//登录的命令
private ICommand _Lgoin = null;
public ICommand Lgoin
{
get { return _Lgoin; }
}
//登录框内容
private string username;
public string Username
{
get { return username; }
set { username = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Username"));
}
}
}
private string pwd;
public string Pwd
{
get { return pwd; }
set { pwd = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Pwd"));
}
}
}
//构造函数
public UserViewModelcs(Collection<User> userlist)
{
this._DataList = userlist;
_Lgoin = new LoginCommand(this);
}
//登录方法
public void login()
{
if (this.Username == "aa")
{
if (this.Pwd == "aa")
{
System.Windows.MessageBox.Show("登录了");
}
}
}
}
}