天天看點

再談WPF

前幾天初步看了一下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("登入了");
                }

            }

        }
    }
}