WinForm数据绑定
使用Prism和DryIoc实现跨窗体数据绑定
开发环境: VS2022 .Net 6.0 WinForm界面程序
要求:
- DryIoc容器注册为单例(Singleton)=>DryIoc
- VM需要实现数据更改通知=>Prism
- 控件数据限幅要一样=>NumericUpDown
🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️
效果:文章来源:https://www.toymoban.com/news/detail-687367.html
- Form2修改Score时Form1立即同步更新
- Form1修改Score时Form1立即同步更新
- 绑定是双向的,增加绑定后VM数据与界面数据自动同步
🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️🍇️文章来源地址https://www.toymoban.com/news/detail-687367.html
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超限会引发异常
}
}
}
到了这里,关于WinForm使用Prism和DryIoc实现跨窗体数据绑定的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!