I am working on a Silverlight application, and I want to bind the simple text property of textblock through a property of string type.
What I did was:
<TextBlock Text="{Binding Name}"/>
Code behind:
public string Name{get;set;}
Name = "Testing..!";
but it will not work.
To expand on anatoliiG’s answer (which will work): Data binding refers to properties on the
DataContextproperty of the current element by default. This means that youris actually translated to
(
DataContextis inherited, so if it is not explicitly set on theTextBlockit will check the parent, then the parent of the parent etc etc)You can resolve your problem in one of two ways:
You can set the value of
this.DataContexton the parent to the parent itself (as anatoliiG suggests). This means that when it looks upthis.DataContext.Nameit will be checking thePageitself, which is where yourNameproperty is found.You can change your
Bindingso it looks at thePageinstead ofPage.DataContextwhen it is looking up bindings. You can achieve this using theRelativeSourcemarkup extension:This translates to:
As a final note, you will also need to implement
INotifyPropertyChangedon yourDataContextobject if you are going to ever change the value ofName.Oh, and you should be using view models as the
DataContextinstead of thePageitself!