NightroadSora
NightroadSora

Reputation: 121

Two Way Binding C# . Textbox and object of self made class

In the MSDN documents I found some articles, which say it wouldn't be any problem to bind two objects to each other. So I tried this with a WindowsForms application. The first object is a TextBox, the second object is an instance of the following class:

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

Binding the TextBox to the XmlEmulator.Captionfield works properly, but how can I bind the Captionfield oroperty to the TextBox.text property? Does the XmlEmulator class have to inherit from the System.Windows.Forms.Control to get the Databindings property? In this case I have run into trouble because I have already implemented the INotifyPropertyChanged Interface.

How can I solve this?

Upvotes: 3

Views: 2168

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205629

In the MSDN documents I found some articles, which say it wouldn't be any problem to bind two objects to each other.

That's not correct, the one one the objects must be a Control, while the other could be any object (including Control). When you bind to a control property, you can specify if the binding is "one way" or "two way", and when to update one or the other side via Binding.DataSourceUpdateMode Property and Binding.ControlUpdateMode Property. I guess your binding is already "two way" if you have used a standard code like this

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

and if you modify the text box, the emulator property will update. Just note that the default value for DataSourceUpdateMode property is OnValidation, so the emulator will be updated after you leave the text box. If you want it to happen immediately as you type, then you need set is to OnPropertyChanged by modifying the above code like this

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

In fact the Add method returns a Binding object, so you can use something like this

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

and explore/modify the binding properties.

Upvotes: 1

Related Questions