Windows Phone : Data Binding

Data Binding is the most important part of developing a good quality dynamic application. You can set the data of a TextBox or some other control by creating various pages and you need to write a lot of code for that and hence data binding helps you to easily bind some data to your controls in creating complex applications.

<TextBlock x:Name="PostNameTextBox" TextWrapping="Wrap"
Text="{Binding PostName}" />
Here we have a TextBlock for a post name, we can have the value of the TextBlock each
time but it will make the code more unhealthy and the practice is not recommended and hence you can notice a
Binding statement that is pointing to something called 
"PostName"PostName here is the property of some
data source and next we need to define the data source by setting the DataContext either on the page or on a
specific element (preferably on the page). These act as objects that says that against any binding statements I will
resolve the data associated with it. So the PostName here is the instance of the data source and once we
have defined the data source it automatically pulls the post name and assigns it to the PostNameTextBox.

Data Binding Modes

There are various binding modes that can be used depending on the requirements of the application:

  1. OneTime

    It means that when the page is rendered any binding statements are resolved against the DataContext. This is done one a single time, in other words if, after resolving the data, there is a change in the data source then it is not reflected back onto the application page.

  2. OneWay

    It gets the data from the data source and there may be a web service or background code running that updates the data source so the UI control gets updates, so it is the synchronized method of data binding.

  3. TwoWay

    It is the next step from OneWay, it does everything OneWay does and can also update the data source for example if a user has a TextBox that the user can enter a data or radio button where a user can select data, and the change goes the other way as well, in other words the data in the data source is also updated. And the best part is that the user doesn't need to write any code to update the data source, it is done automatically.

    <TextBlock x:Name="PostNameTextBox" TextWrapping="Wrap"Text="{Binding PostName, Mode=TwoWay}"  />

So now with data binding we have much more cleaner code that is much easeir to maintain and a healthy programming practice.

Up Next
    Ebook Download
    View all
    Learn
    View all