views:

229

answers:

2

I have a basic property that stores an object of type Fruit:

Fruit food;
public Fruit Food
{
    get {return this.food;}
    set
    {
     this.food= value;
     this.RefreshDataBindings();
    }
}

public void RefreshDataBindings()
{
    this.textBox.DataBindings.Clear();
    this.textBox.DataBindings.Add("Text", this.Food, "Name");
}

So I set this.Food outside the form and then it shows up in the UI.

If I modify this.Food, it updates correctly. If I modify the UI programmatically like:

this.textBox.Text = "NewFruit", it doesn't update this.Food.

Why could this be? I also implemented INotifyPropertyChanged for Fruit.Name, but still the same.

A: 

You can't databind to a property and then explictly assign a value to the databound property.

hjb417
Thanks, but why is this not possible? I thought it's 2 way?
Joan Venge
Joan, that is the (much improved) binding in WPF. WinForms is relatively simple.
Henk Holterman
Thanks Henk, do you know how to achieve this in Winforms? I can't use wpf for this project unfortunately.
Joan Venge
+2  A: 

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text", this.Food, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Joepro