【问题标题】:Simple databinding between textbox and form title文本框和表单标题之间的简单数据绑定
【发布时间】:2010-07-08 22:55:41
【问题描述】:

我是 C# 和数据绑定的新手,作为一个实验,我试图将表单标题文本绑定到一个属性:

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")

然后它就可以正常工作了。

任何关于为什么第一个代码示例不起作用的解释将不胜感激。

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    您必须实现 INotifyPropertyChanged 接口。 试试下面的代码,看看当你从 setter 中删除 NotifyPropertyChanged("MyProperty"); 时会发生什么:

    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; 
    }
    

    【讨论】:

    • +1 需要包含 TextChanged 处理程序,以便设置属性,这是我缺少的另一部分。
    【解决方案2】:

    我认为您需要实现 INotifyPropertyChanged 接口。您必须在 Windows 窗体数据绑定中使用的业务对象上实现此接口。实现后,该接口会将业务对象的属性更改与绑定控件进行通信。

    How to: Implement the INotifyPropertyChanged Interface

    【讨论】:

    • 感谢您的链接,这是我错过的重要内容。但是,似乎还需要始终通过属性设置该值才能使其正常工作,因此在我的示例中还需要 TextChanged 处理程序。
    猜你喜欢
    • 2010-12-16
    • 2011-08-31
    • 2016-12-28
    • 2018-08-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多