双向绑定C#.自制类的文本框和对象

本文关键字:文本 对象 绑定 | 更新日期: 2023-09-27 18:23:48

在MSDN文档中,我发现了一些文章,其中说将两个对象相互绑定不会有任何问题。所以我在WindowsForms应用程序中尝试了一下。第一个对象是TextBox,第二个对象是以下类的实例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace WindowsFormsApplication1
{
public class XmlEmulator : INotifyPropertyChanged
{
    private string Captionfield;
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged()
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(""));
    }
    public string Caption
    {
        get
        {
            return this.Captionfield;
        }
        set
        {
            this.Captionfield = value;
            NotifyPropertyChanged();
        }
    }
}
}

TextBox绑定到XmlEmulator.Captionfield可以正常工作,但如何将Captionfield或属性绑定到TextBox.text属性?XmlEmulator类是否必须从System.Windows.Forms.Control继承才能获得Databindings属性?在这种情况下,我遇到了麻烦,因为我已经实现了INotifyPropertyChanged接口。

我该如何解决这个问题?

双向绑定C#.自制类的文本框和对象

在MSDN文档中,我发现了一些文章,其中说将两个对象相互绑定不会有任何问题。

这是不正确的,其中一个对象必须是Control,而另一个可以是任何对象(包括Control)。绑定到控件属性时,可以指定绑定是"单向"还是"双向",以及何时通过binding.DataSourceUpdateMode属性和binding.ControlUpdateMode属性更新一侧或另一侧。如果你使用了像这样的标准代码,我想你的绑定已经是"双向"的了

XmlEmulator emulator = ...;
TextBox textBox = ....;
textBox.DataBindings.Add("Text", emulator, "Caption");

如果修改文本框,则模拟器属性将更新。只需注意,DataSourceUpdateMode属性的默认值是OnValidation,因此模拟器将在您离开文本框后更新。如果你想在输入时立即发生,那么你需要通过修改上面的代码(如)将is设置为OnPropertyChanged

textBox.DataBindings.Add("Text", emulator, "Caption", true, DataSourceUpdateMode.OnPropertyChanged);

事实上,Add方法返回一个Binding对象,所以您可以使用类似于的东西

var binding = textBox.DataBindings.Add("Text", emulator, "Caption");

并探索/修改结合特性。