Jim_CS
Jim_CS

Reputation: 4172

Databinding works for string but won't work for string inside an object

So I have a String property bound to the Text property of a Textbox and it works fine -

public String MyString { get; set; }
MyString = "Hello World";
<TextBox Text="{Binding Path=MyString}"....

However when I try to bind using a string inside an object it doesn't work...like so

public class MyObject
{
    public String MyString { get; set; }
}

MyObject myObject = new MyObject();
myObject.MyString = "Hello World";
<TextBox Text="{Binding Path=myObject.MyString}"...

I cannot understand why this isn't binding. All I have done is put the string inside a class and then changed the xaml to reflect that. Any ideas what's going wrong?

Upvotes: 0

Views: 110

Answers (3)

Xcalibur37
Xcalibur37

Reputation: 2323

I agree with John. You should be using INotifyPropertyChanged or a Dependency Property to properly bind the property to your UI. It's very possible that the binding is working, but appears as an empty string because the bind occurred before the value was set.

When do you set your DataContext?

Upvotes: 0

Marty
Marty

Reputation: 7522

You need to expose the myObject instance with a property on your ViewModel, instead of just using a local variable (which you appear to be doing based on the code you posted). Something like this:

public MyObject Obj { get; set; }

Obj = new MyObject()  { MyString = "Hello World" };

and in your XAML:

<TextBox Text="{Binding Path=Obj.MyString}" ...

Upvotes: 1

brunnerh
brunnerh

Reputation: 185180

You might be making the changes after the binding takes place and since you do not appear to implement INPC there are no updates to the binding once the string/object is set.

(You might also want to have a look at the overview if you are not that familiar with bindings.)

Upvotes: 0

Related Questions