代码之家  ›  专栏  ›  技术社区  ›  WildCrustacean

文本框和表单标题之间的简单数据绑定

  •  3
  • WildCrustacean  · 技术社区  · 14 年前

    namespace BindTest
    {
        public partial class Form1 : Form
        {
            public string TestProp { get { return textBox1.Text; } set { } }
    
            public Form1()
            {
                InitializeComponent();
                this.DataBindings.Add("Text", this, "TestProp");
            }
        }
    }
    

    不幸的是,这不起作用。我怀疑这与不发送事件的属性有关,但我对数据绑定的了解还不够,不知道具体原因。

    如果我将标题文本直接绑定到文本框,如下所示:

    this.DataBindings.Add("Text", textBox1, "Text")
    

    那么它就可以正常工作了。

    请解释为什么第一个代码示例不起作用。

    2 回复  |  直到 14 年前
        1
  •  3
  •   Å¡ljaker    14 年前

    必须实现INotifyPropertyChanged接口。 尝试下面的代码,看看删除时会发生什么 NotifyPropertyChanged(“MyProperty”); 来自setter:

    private class MyControl : INotifyPropertyChanged
    {
        private string _myProperty;
        public string MyProperty
        {
            get
            {
                return _myProperty;
            }
            set
            {
                if (_myProperty != value)
                {
                    _myProperty = value;
                    // try to remove this line
                    NotifyPropertyChanged("MyProperty");
                }
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    private MyControl myControl;
    
    public Form1()
    {
        myControl = new MyControl();
        InitializeComponent();
        this.DataBindings.Add("Text", myControl, "MyProperty");
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        myControl.MyProperty = textBox1.Text; 
    }
    
        2
  •  1
  •   Leniel Maccaferri    14 年前

    我认为您需要实现INotifyPropertyChanged接口。必须在Windows窗体数据绑定中使用的业务对象上实现此接口。在实现时,接口将业务对象的属性更改传递给绑定控件。

    How to: Implement the INotifyPropertyChanged Interface