ViewModel:
public class UserModel : BindableBase
{
private int id= 0;
private string name = string.Empty;
private string address = string.Empty;
///
/// Id
///
public int Id { get => id; set => SetProperty(ref id, value); }
///
/// 名称
///
public string Name { get => name; set => SetProperty(ref name, value); }
///
/// 地址
///
public string Address { get => address; set => SetProperty(ref address, value); }
}
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty
{
if (!EqualityComparer
{
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
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
{
List
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));
}
}
}