Revision as of 04:27, 10 April 2013 by hamishwillee (Talk | contribs)

Data Binding in Qt and Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article demonstrates how to work with Data Binding in Qt and WP7. See QML Property Binding and Data Binding (MSDN) for a more detailed overview.

See Also
WP Metro Icon Porting.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone SDK 7.1 for Windows Phone and Qt SDK for Qt Code
Devices(s): WP7 Emulator
Keywords: Binding
Created: somnathbanik (23 Oct 2011)
Updated: hamishwillee (25 Apr 2012)
Last edited: hamishwillee (10 Apr 2013)



Data binding is a technique that binds two data/information sources together and maintains synchronization of data. In both Qt and Windows Phone data binding is used to synchronise UI components to each other and to the application engine/business logic.

Data Binding Diagram

In this simple example we create two controls, one for text entry and the other for displaying the entered text. Data binding is used to ensure that the content of the controls is synchronised. Screenshots of both apps are shown below.


Qt Project (main.qml)

Data binding between QML objects in the same file is trivially easy: simply assign the property of source object into the target object property.

So for example, we create a source TextField (id:sourceTextField) and a target Text QML Element (id:targetText).

TextField {
id: sourceTextField;
width: parent.width -80
text: "Enter Text Here"
errorHighlight: true
anchors.horizontalCenter: parent.horizontalCenter
//The target text element
Text {
text: sourceTextField.text //Data binding!
font.pixelSize: 25
font.bold: true
color: "green"

To bind the source and target, we assign sourceTextField's text property to targetText's text property.

text: sourceTextField.text //Data binding!

Sometimes we need to bind to a property of an object that wasn't directly instantiated by QML - generally a property of a class exported to QML by C++. In this case you can use the QML Binding Element to bind any element to any value:

Binding { target: targetText; property: "text"; value: sourceTextField.text }

WP7 Project (MainPage.xaml)

The Windows Phone example is very similar. We create a TextBox for text entry and a TextBlock for displaying the entered data.

<TextBox Height="72" HorizontalAlignment="Left" Margin="35,191,0,0" 
Name="sourceTextBox" Text="TextBox" VerticalAlignment="Top" Width="381" />
<TextBlock Foreground="Green" FontStyle="Italic" FontFamily="Times New Roman" FontSize="35" Height="63" HorizontalAlignment="Left" Margin="50,367,0,0"
Name="targetTextBlock" Text="{Binding Text, ElementName=sourceTextBox}" VerticalAlignment="Top" Width="350" />

The data binding is declared in the targetTextBlock using the Binding syntax:

Text="{Binding Text, ElementName=sourceTextBox}

Source Code

141 page views in the last 30 days.