WinForm数据绑定
使用Prism和DryIoc实现跨窗体数据绑定
开发环境: VS2022 .Net 6.0 WinForm界面程序
要求:
- DryIoc容器注册为单例(Singleton)=>DryIoc
- VM需要实现数据更改通知=>Prism
- 控件数据限幅要一样=>NumericUpDown
🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️
效果:
- Form2修改Score时Form1立即同步更新
- Form1修改Score时Form1立即同步更新
- 绑定是双向的,增加绑定后VM数据与界面数据自动同步
🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️
internal static class Program
{
[NotNull]
internal static DryIoc.Container? Ioc { get; set; }
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Ioc = new DryIoc.Container();
Application.Run(new Form1());
Ioc.Dispose();
}
}
// Form1
public partial class Form1 : Form
{
public Form1VM VM { get; set; }
public Form1()
{
Program.Ioc.RegisterMany<Form1VM>(Reuse.Singleton);
VM = Program.Ioc.Resolve<Form1VM>();
VM.ScoreMin = 0.5M;
num1.DataBindings.Add(new Binding("Value", VM, "ScoreMin", false, DataSourceUpdateMode.OnPropertyChanged));
}
private void btn_f2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
// f2.Dispose(); // ShowDialog时使用
}
}
// Form2
public partial class Form2 : Form
{
public Form1VM VM { get; set; }
public Form2()
{
InitializeComponent();
VM = Program.Ioc.Resolve<Form1VM>();
}
private void Form2_Load(object sender, EventArgs e)
{
num1.DataBindings.Add(new Binding("Value", VM, "ScoreMin", false, DataSourceUpdateMode.OnPropertyChanged));
this.TopMost = true;
}
}
public class Form1VM : BindableBase, IVM
{
private decimal _ScoreMin;
public decimal ScoreMin
{
get
{
return _ScoreMin;
}
set
{
//var tmp = Math.Clamp(value, 0.3M, 1M);
SetProperty(ref _ScoreMin, value); // Form2超限会引发异常
}
}
}