最近在学习Wpf,学到了Wpf中最重要的双向绑定,在这做个笔记
要想实现控件和后台代码的双向绑定,就必须继承INotifyPropertyChanged这个接口,并且实现PropertyChangedEventHandler这个事件,话不多说,上代码:
这个是后台代码
public partial class MainWindow : Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
//public string UserName { get; set; }
//public string PassWord { get; set; }
//双向绑定
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private string usename;
public string UserName
{
get { return usename; }
set { usename = value;RaisePropertyChanged("UserName"); }
}
private string password;
public string PassWord
{
get { return password; }
set { password = value;RaisePropertyChanged("PassWord"); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//string userName = txtUserName.Text;
//string passWord = txtPassword.Text;
if (UserName == "Wpf" && PassWord == "666")
{
index index = new index();
index.Show();
this.Close();
}
else
{
MessageBox.Show("账号密码错误", "警告");
UserName = "";
PassWord = "";
}
}
}
这个是前端xaml代码
<Window x:Class="Wpf_loginUi.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Wpf_loginUi"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="9*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="0" Text="宝安区-区图书馆系统" FontSize="18" Foreground="Black" HorizontalAlignment="Center"/>
<StackPanel Grid.Row="1" Grid.Column="0" Background="#0078d4">
<TextBlock Margin="5" Text="登录" FontSize="22" HorizontalAlignment="Center" Foreground="White"/>
</StackPanel>
<Grid Grid.Row="3" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<TextBlock Text="用户名" Grid.Row="0" Grid.Column="0"/>
<TextBox Grid.Row="0" Text="{Binding UserName}" Grid.Column="1" Margin="2"/>
<TextBlock Text="密码" Grid.Row="1" Grid.Column="0"/>
<TextBox Grid.Row="1" Text="{Binding PassWord}" Grid.Column="1" Margin="2"/>
<CheckBox Content="记住密码" Grid.Row="2" Grid.ColumnSpan="2"/>
<Button Grid.Row="3" Content="登录" Grid.ColumnSpan="2" Click="Button_Click"/>
</Grid>
</Grid>
</Window>