gpt4 book ai didi

c# - Windows 窗体数据绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:04 25 4
gpt4 key购买 nike

所以,我的问题是关于 Windows 窗体数据绑定(bind)背后的确切方法。

我写了一段简单的代码,其中我创建了一个 View 、一个 IViewModel 接口(interface)和一个 ViewModel。

interface IVM
{
}

public class Vm : IVM
{
int number;
public int Number
{
get
{
return this.number;
}

set
{
this.number = value;
}
}
}

表单如下所示:

public partial class Form1 : Form
{
private IVM vm;

public Form1()
{
InitializeComponent();
this.vm = new Vm();

this.iVMBindingSource.DataSource = this.vm;
}
}

相关的设计器部分是:

this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.iVMBindingSource, "Number", true));
...
this.iVMBindingSource.DataSource = typeof(WindowsFormsApplication1.IVM);

可以清楚地看到 IViewModel 接口(interface)没有发布 Number 属性,但是具体的 ViewModel 类有一个 Number 属性。

虽然在设计时我不能使用设计器来绑定(bind)属性(因为 IVM 没有 Number 属性),我可以手动将“iVMBindingSource - Number”写入文本框的 Test 属性,以绑定(bind)它。

我的问题是,绑定(bind)究竟是如何工作的?为什么我在尝试访问 IVM 不存在的 Number 属性时没有收到运行时错误?(我测试过它实际上正确地改变了 VM 的 Number 属性)

它是否使用某种反射?这个“神奇”的绑定(bind)字符串是如何工作的?

感谢您的回答!

最佳答案

Jup 这是通过反射完成的。我刚刚检查了代码,绑定(bind)是由 Binding 类完成的。有一个名为 CheckBindings 的方法可确保您要绑定(bind)的属性可用。它基本上是这样工作的:

if (this.control != null && this.propertyName.Length > 0)
{
// ...certain checks...
// get PropertyDescriptorCollection (all properties)
for (int index = 0; index < descriptorCollection.Count; ++index)
{
// select the descriptor for the requested property
}
// validation
// setup binding
}

如 Ike 所述,您可以在此处找到源代码: http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Binding.cs,3fb776d540d0e8ac

MSDN 引用:https://msdn.microsoft.com/en-us/library/system.windows.forms.binding(v=vs.110).aspx

关于c# - Windows 窗体数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com