1.创建一个ViewModel类
在这里插 internal class VMBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}入代码片
2.创建一个Mvm类继承VMBase
internal class MVM:VMBase
{
private string firstName="Fn";
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
OnPropertyChanged();
OnPropertyChanged();
}
}
private string lastName="Ln";
public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged();
OnPropertyChanged();
}
}
private string fullName="FUllName";
public string FullName
{
get { return fullName; }
set {
fullName = value;
OnPropertyChanged();
OnPropertyChanged();
}
}
}
```3.主窗体实现
```csharp
在这里插 MVM mVM = new MVM();
private void Form1_Load(object sender, EventArgs e)
{
label1.DataBindings.Add("Text", mVM,"FirstName");//控件的属性字符串,数据源,属性的字符串,是否格式化,数据更新方式
label2.DataBindings.Add("Text", mVM, "LastName",false, DataSourceUpdateMode.OnPropertyChanged);
label3.DataBindings.Add("Text", mVM, "FullName", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
mVM.FirstName = textBox1.Text;
mVM.FullName = textBox1.Text+textBox2.Text;
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
mVM.LastName = textBox2.Text;
mVM.FullName = textBox1.Text + textBox2.Text;
}入代码片
```使用[CallerMemberName]避免在触发事件输入属性的字符串,更加方便!