首页 > 解决方案 > VB和C#之间的绑定问题

问题描述

在 C# 中,我有以下代码

txtCode.DataBindings.Add(new Binding("Text", _bsDetail, "Code", true, DataSourceUpdateMode.OnPropertyChanged));

在 VB.NET 中

txtCode.DataBindings.Add(new Binding("Text", _bsDetail, "Code", true, DataSourceUpdateMode.OnPropertyChanged))

在 C# 中,我可以在绑定源上设置数据源之前调用此代码,在 VB.NET 中,我必须在调用此代码之前分配数据源。我在 VB.NET 中收到以下错误

无法绑定到数据源上的属性或列代码。参数名称:dataMember'

有没有办法在 VB.NET 中分配数据源之前调用此代码?

标签: c#vb.net

解决方案


有没有办法在 VB.NET 中分配数据源之前调用此代码?

是的,它与 C# 中使用的代码序列相同。C# 中没有任何固有的东西允许您描述的内容。

为了证明这一点,创建一个新的 C# Winform 项目并将以下代码添加到 Form1。

BindingSource bs;
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    bs = new BindingSource();
    Debugger.Break();
    Binding b = new Binding("Text", bs, "Code", true, DataSourceUpdateMode.OnPropertyChanged);
    this.DataBindings.Add(b);
}

现在运行代码,当调试器中断时,单步执行代码。您将在最后一行看到错误。这是堆栈跟踪的摘录。CheckBinding 方法中发生错误,因为BindingSource尚未分配DataSource公开Code属性的 a。

在 System.Windows.Forms.BindToObject.CheckBinding() 在 System.Windows.Forms.BindToObject.SetBindingManagerBase(BindingManagerBase lManager) 在 System.Windows.Forms.Binding.SetListManager(BindingManagerBase bindingManagerBase) 在 System.Windows.Forms.ListManagerBindingsCollection.AddCore (Binding dataBinding) at System.Windows.Forms.BindingsCollection.Add(Binding binding) at System.Windows.Forms.BindingContext.UpdateBinding(BindingContext newBindingContext, Binding binding) at System.Windows.Forms.Binding.SetBindableComponent(IBindableComponent value) at System.Windows.Forms.ControlBindingsCollection.AddCore(绑定数据绑定)在 System.Windows.Forms.BindingsCollection.Add(绑定绑定)在 System.Windows.Forms.ControlBindingsCollection.Add(绑定绑定)

可以通过将 置于初始化状态来抑制BindingSource绑定检查BindingSource实现公开BeginInit 方法的ISupportInitialize 接口。将代码替换为以下内容:OnLoad

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    bs = new BindingSource();
    ISupportInitialize isi = (ISupportInitialize)bs;
    Debugger.Break();
    isi.BeginInit();
    Binding b = new Binding("Text", bs, "Code", true, DataSourceUpdateMode.OnPropertyChanged);
    this.DataBindings.Add(b);
    isi.EndInit();
}

运行代码并再次单步调试调试器中的代码。您将看到错误没有出现在DataBindings.Add语句中,而是出现在EndInit 方法中,在该点CheckBindings最终被调用并失败,因为没有提供数据源。

在 System.Windows.Forms.BindToObject.CheckBinding() 在 System.Windows.Forms.BindToObject.DataSource_Initialized(Object sender, EventArgs e) 在 System.Windows.Forms.BindingSource.OnInitialized() 在 System.Windows.Forms.BindingSource。 System.ComponentModel.ISupportInitialize.EndInit()

所以简化的代码模式是:

  1. 创建一个 BindingSource 实例。
  2. 在 BindingSource 上调用 BeginInit。
  3. 针对 BindingSource 创建/添加所有绑定。
  4. 设置 BindingSource.DataSource 属性。
  5. 在 BindingSource 上调用 EndInit。

这种模式与所使用的语言无关。


推荐阅读