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

3

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

然后它会正确地工作。

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

2个回答

3
你必须实现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; 
}

需要在TextChanged处理程序中添加+1,以便设置属性,这是我缺少的另一部分。 - WildCrustacean

1
我认为你需要实现INotifyPropertyChanged接口。你必须在用于Windows Forms数据绑定的业务对象上实现此接口。当实现时,该接口会向绑定控件通信业务对象的属性更改情况。

如何实现INotifyPropertyChanged接口


谢谢提供链接,这是我缺失的重要部分。然而,似乎该值也需要始终通过属性设置才能起作用,因此在我的示例中,TextChanged处理程序也是必需的。 - WildCrustacean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接