【问题标题】:C# data binding not working for unknown reasonC# 数据绑定因未知原因无法正常工作
【发布时间】:2014-08-04 06:23:24
【问题描述】:

我想用数据绑定做一些非常简单的事情,但这根本行不通。这就是我想做的:

1,我想和设计师一起做,因为我不想管理代码,这是我使用这个 IDE 的全部目的。
2、当用户在文本框中编辑时,我的类中的一个字符串变量发生了变化。
3、当程序编辑字符串变量时,该文本框中的文本发生变化。

这是我为它编写的代码:

public partial class frmMain : Form, INotifyPropertyChanged

....

private string _btxtChars;
[System.ComponentModel.Bindable(true)]
public string btxtChars { 
    get 
    { 
        return _btxtChars; 
    } 
    set 
    { 
        _btxtChars = value; 
        OnPropertyChanged("btxtChars"); 
    } 
}

....

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string info)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(info));
            }
        }

我在我的设计器中设置了相应的属性,导致以下代码:

this.txtCharToAdd.DataBindings.Add(
    new System.Windows.Forms.Binding("Text", 
        this.frmMainBindingSource, 
        "btxtChars", 
        true, 
        System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)
    );

现在,当我编辑变量 btxtchars 时,没有任何反应。我做错了什么?

【问题讨论】:

  • 什么是frmMainBindingSource 以及如何分配DataSource 属性?
  • frmMainBindingSource 是由 IDE 创建的,我不知道它为什么在那里。

标签: c# winforms data-binding


【解决方案1】:

您应该按如下方式初始化您的 BindingSource 以启动与您的表单作为数据存储对象的绑定:

public partial class frmMain : Form, INotifyPropertyChanged {
    public frmMain() {
        InitializeComponent(); 
        // you can see that the InitializeComponent method contains the following line: 
        // this.frmMainBindingSource.DataSource = typeof(WindowsFormsApplication1.frmMain);

        frmMainBindingSource.DataSource = this; // you should either replace the line above or initiate binding here
    }
//...

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多