1、继承属性变化接口
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
2.创建被绑定属性
private string _userName;
public string UserName
{
get { return _userName; }
set { _userName = value;
RaisePropertyChanged("UserName");
}
}
3.界面绑定属性
<TextBox Text="{Binding UserName}" Grid.Row="0" Grid.Column="1" Margin="2"/>
4.界面数据关联属性
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
5.使用绑定属性
if (UserName == "WPF" && passWord == "123")
{
IndexWindow indexWindow = new IndexWindow();
indexWindow.Show();
this.Hide();
}
else
{
MessageBox.Show("输入的用户名或密码不正确");
UserName = "";
txtPassword.Text = "";
}
完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF_LoginUI
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private string _userName;
public string UserName
{
get { return _userName; }
set { _userName = value;
RaisePropertyChanged("UserName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private void BtnLogin_Click(object sender, RoutedEventArgs e)
{
string passWord = txtPassword.Text;
if (UserName == "WPF" && passWord == "123")
{
IndexWindow indexWindow = new IndexWindow();
indexWindow.Show();
this.Hide();
}
else
{
MessageBox.Show("输入的用户名或密码不正确");
UserName = "";
txtPassword.Text = "";
}
}
}
}