Data binding in Windows Phone app – One way binding

Data binding provides a simple way for Windows Phone apps to display and interact with data. In simple terms it provides a link between the target and source. For example if we consider a Textblock and a data source whose object needs to update the value of text in Textblock we can use data binding.

 

We will now explain One way data binding in which bindings update the target with the source data when the binding is created.

Here source is a object of the class which needs to update the text property of Textblock (target).

 

The steps that need to be followed are

 

1. First of all create a blank project and name it Databinding .

 


 

2. Replace the Xaml code of the Stackpanel named Titlepanel with the following code given below.

 


 

Code:

<StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,17,0,28″>

<TextBlock Text=”Databinding” Style=”{StaticResource PhoneTextNormalStyle}” Margin=”12,0″/>

<TextBlock Text=”One way” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>

</StackPanel>

 

3. Add a Textblock named myblock to the given page . And bind the text property of the Textblock with mytext which is the property of the Sample class which will be explained further.

 



 

Add the code given below to the Grid named ContentPanel given on the page

Code:

<TextBlock x:Name=”myblock” HorizontalAlignment=”Left” Margin=”63,80,0,0″ TextWrapping=”Wrap” Text=”{Binding mytext}” VerticalAlignment=”Top” Height=”57″ Width=”330″ FontSize=”28″/>

 

4. Open the Page MainPage.xaml.cs and Create a Public class having the name Sampleclass with a single property mytext.

 


 

Code:

public class Sampleclass

{

public string mytext { get; set; }

}

 

5. Add the function given below to the MainPage.xaml.cs .

 

Code:

public void initialize()

{

Sampleclass obj = new
Sampleclass();

obj.mytext = “One way data binding”;

myblock.DataContext = obj;

}

 

In the first line of the function we are creating a object of Sampleclass called obj. In the second line we are setting the mytext property of the object to “One way data binding”.

In the third line we set the source of the myblock by setting up its Datacontext property to obj.

 

6. We then call this function in the constructor of the MainPage.

 


 

7. Now when we run the application we will see that the Content of myblock will be “One way data binding” as shown below.

 


 

8. I hope this post will be helpful to you.Download the project zip file from the link given below.

 

Download full project