views:

5286

answers:

7

I have the following class

public class Car
{
   public Name {get; set;}
}

and I want to bind this programmatically to a text box.

How do I do that?

Shooting in the dark:

...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...

I get the following error "Cannot bind to the propery 'Name' on the target control.

What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.

+6  A: 

without looking at the syntax, I'm pretty sure it's

editBox.DataBinding.Add("Text", car, "Name");

Danimal
+1  A: 

You're trying to bind to the "Name" of the TextEdit control. The name is used for accessing the control programmatically, and cannot be bound against. You should be binding against the Text of the control.

Will
+19  A: 

You want

editBox.DataBindings.Add("Text", car, "Name");

The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to.

ageektrapped
+3  A: 

Try:

editBox.DataBinding.Add( "Text", car", "Name" );
TcKs
+2  A: 

I believe that

editBox.DataBindings.Add(new Binding("Text", car, "Name"));

should do the trick. Didn't try it out, but I think that's the idea.

itsmatt
+3  A: 
editBox.DataBinding.Add("Text", car, "Name");

First arg is the name of the control property, the second is the object to bind, and the last, the name of the object property you want to use as the data source.

Romain Verdier
+3  A: 

You are quite close the data bindings line would be

editBox.DataBinding.Add("Text", car, "Name");

This first parameter is the property of your editbox object that will be data bound. The second parameter is the data source you are binding to and the last parameter is the property on the data source that you want to bind to.

Bear in mind that the data binding is one way so if you change the edit box then the car object gets updated but if you change the car name directly the edit box is not updated.

John Hunter