WPF 可以把控件的值绑定到某个数值对象,绑定也有很多方法。这里,我们把整个窗口的所有控件的值绑定到一个类的对象中,这个类就是专门负责数据管理的类。其实质就是和Window类的DataContext共享源,非常推荐这种方式,因为数据管理类还可以一块把数据保存到文件,加载窗口的时候也可以自动从文件中读取数据,不需要专门设置。
- 在项目中添加一个Data类(如代码3),该类继承自INotifyPropertyChanged,该继承是为了当数据有变化时,能通知UI更新数据;
- 在Window的xaml文件中给对应控件添加Binding数据(如代码1);
- 在Windowl的类的构造函数中给DataContext添加Data类的对象(如代码2);
此时就已经完成了数据的绑定,UI控件的值会自动更新到Data对象中,Data对象通过调用NotifyPropertyChanged()函数可以通知UI更新数据。但是目前的代码直接拷贝过去还是编译不过的,因为我的Data类还做了一件事情:那就是把用户名、密码直接存到配置文件。
在项目中添加一个SettingFile,如下图。

给SettingFile添加两个字段user,和password。

此时,代码3中的DataFile.Default.user和DataFile.Default.password,就是指的这两个值了,它们是存储在文件中的,存在Windows的C:\Users\YourUserName\AppData\Local\YourCompanyName\YourAppName目录下。
此时,再编译就可以运行了。
代码1:数据Binding示例:
<TextBox Text="{Binding user, Mode=TwoWay}">
<PasswordBox Text="{Binding password, Mode=TwoWay}">
<TextBox Text="{Binding info, Mode=TwoWay}">
代码2:DataContext指定对象:
namespace Test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Data();
}
}
}
代码3:Data类示例:
// 数据管理类,负责界面所有数据的绑定。只要绑定好,就可以自动保存数据到setting文件、创建窗口的时候自动读数据。
// 使用的时候一定不要忘了在窗口类的构造函数中添加“this.DataContext = new Data();”
// xaml中只需要binding到类的相应成员名即可(不支持的数据类型除外,那需要专门转换)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel; // for INotifyPropertyChanged
namespace Test
{
class Data: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string user // 用户名
{
get { return DataFile.Default.user; }
set
{
DataFile.Default.user = value;
DataFile.Default.Save();
NotifyPropertyChanged();
}
}
public string password // 密码
{
get { return DataFile.Default.password; }
set
{
DataFile.Default.password = value;
DataFile.Default.Save();
NotifyPropertyChanged();
}
}
private string _info;
public string info
{
get
{
if (this._info == null || this._info.Length == 0)
this._info = "This is my information!";
return this._info;
}
set
{
if (value != this._info)
{
this._info = value;
NotifyPropertyChanged();
}
}
}
}
}