ViewModel:
public class UserModel : BindableBase
{
private int id= 0;
private string name = string.Empty;
private string address = string.Empty;
/// <summary>
/// Id
/// </summary>
public int Id { get => id; set => SetProperty(ref id, value); }
/// <summary>
/// 名称
/// </summary>
public string Name { get => name; set => SetProperty(ref name, value); }
/// <summary>
/// 地址
/// </summary>
public string Address { get => address; set => SetProperty(ref address, value); }
}
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
View:
public partial class Form1 : Form
{
private UserModel VMUserModel;
public Form1()
{
VMUserModel = new UserModel()
{
Num = 0,
Name = "",
Birthday = "",
Age = 0,
Address = ""
};
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
List<Control> list = GetAllControl(this);
var propes = VMUserModel.GetType().GetProperties();
//textBox3.DataBindings.Add(new Binding("Text", VMUserModel, "Num"));
foreach (Control item in list)
{
var prop = propes.FirstOrDefault(a => item.Tag != null && a.Name == item.Tag.ToString());
if (prop != null)
{
if (item is Label) item.DataBindings.Add(new Binding("Text", VMUserModel, prop.Name));
if (item is TextBox) item.DataBindings.Add(new Binding("Text", VMUserModel, prop.Name));
if (item is CheckBox) item.DataBindings.Add(new Binding("Checked", VMUserModel, prop.Name));
if (item is ComboBox) item.DataBindings.Add(new Binding("SelectedItem", VMUserModel, prop.Name));
}
}
}
public List<Control> GetAllControl(Control ctl)
{
List<Control> result = new List<Control>();
if (ctl.HasChildren)
{
if (!(ctl is Form)) result.Add(ctl);
foreach (Control item in ctl.Controls)
{
result.AddRange(GetAllControl(item));
}
}
else
{
result.Add(ctl);
}
return result;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(JsonConvert.SerializeObject(VMUserModel));
}
}
}