×
Namespaces

Variants
Actions
(Difference between revisions)

Data Binding to controls on Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
chintandave_er (Talk | contribs)
(Chintandave er - updated keyword in ArticleMetaData)
hamishwillee (Talk | contribs)
m (Hamishwillee - Minor subedit)
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Code Examples]]
+
[[Category:Windows Phone]][[Category:General Programming]][[Category:Files/Data]][[Category:Code Examples]]
{{Abstract|This article explains how to bind data to your windows phone application. Article shows how to bind data
+
{{Abstract|This article explains how bind data objects in code to objects declared in your Windows Phone app's XAML UI.}}
in XAML files and later on also explains how to update data in UI components using INotifyPropertyChanged interface class.
+
}}
+
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= [[Media:DataBindingEx.zip]]
 
|sourcecode= [[Media:DataBindingEx.zip]]
Line 13: Line 11:
 
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
|keywords= [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged]
+
|keywords= INotifyPropertyChanged
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
Line 27: Line 25:
  
 
== Introduction ==
 
== Introduction ==
Each and every application of windows phone contains some sort 6f data and its very important to link those data to the UI elements and their attributes. Data binding is one of the most important development techniques that is used to provide user with visual representation of the data. It connects the underlying data source with the user interface and enables data
+
Windows Phone apps typically define their UI declaratively using XAML (in Expression Blend). While some UI component values may be hardcoded in XAML, many will be provided by data sources (objects, databases, XML feeds). Data binding is the technique which provides the connection between the XAML components and their values as defined in code.
manipulation and navigation.
+
 
 +
This article shows how define user elements in XAML and bind their data values to an object defined in the C# file. It also shows how to use the [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v&#61;vs.95%29.aspx INotifyPropertyChanged] interface class to ensure that the UI is updated whenever the underlying code changes.
  
 
== Getting Started ==
 
== Getting Started ==
To understand binding lets create an example application for Windows Phone 7.1 O/S and add a new class to it. New class is the model class which will contain the data properties, and  
+
To understand binding lets create an example application for Windows Phone 7.5 and add a new class to it. New class is the model class which will contain the data properties, and will bind those data properties to UI elements in XAML file without any cs code.
will bind those data properties to UI elements in XAML file without any cs code.
+
  
 
<code csharp>
 
<code csharp>
Line 47: Line 45:
 
</code>
 
</code>
  
PhoneModel.cs contains all the properties you want to show in your UI form, for example at present we have three textbox and they will show all the three properties declared in the PhoneModel class.
+
'''PhoneModel.cs''' contains all the properties you want to show in your UI form, for example at present we have three textbox and they will show all the three properties declared in the {{Icode|PhoneModel}} class.
  
 
== Creating the UI ==
 
== Creating the UI ==
Line 77: Line 75:
  
 
== Lets Bind Now ==
 
== Lets Bind Now ==
The above XAML code contains hard-coded data values. To bind the properties first we need to identify the attribute of the UI element which needs to be binded,  
+
The above XAML code contains hard-coded data values. To bind the properties first we need to identify the attribute of the UI element which needs to be bound, then we need to use the keyword {{Icode|Binding}} in curly braces and need to specify the name of the property to which we need to bind, e.g. textbox text attribute.
then we need to use the keyword Binding in curly braces and need to specify the name of the property to which we need to bind, e.g. textbox text attribute  
+
 
we will bind with the manufacturer property of PhoneModel.cs . Now the updated XAML code looks like:
+
We will bind with the manufacturer property of '''PhoneModel.cs'''. Now the updated XAML code looks like:
  
 
<code xml>
 
<code xml>
Line 89: Line 87:
 
</code>
 
</code>
  
To identify the changes please observe the text attribute of any of the TextBox in the Grid, the attribute now have binding with the manufacturer property of PhoneModel class.
+
To identify the changes please observe the text attribute of any of the {{Icode|TextBox}} in the {{Icode|Grid}}, the attribute now have binding with the manufacturer property of {{Icode|PhoneModel}} class.
  
Still its not clear how the XAML knows which object and its property it needs to bind, i mean to say which class the XAML should look for properties mention in the  
+
Still its not clear how the XAML knows which object and its property it needs to bind, I mean to say which class the XAML should look for properties mention in the text attribute of the textbox.
text attribute of the textbox.
+
  
To make that happen we will use something known as DataContext. DataContext is the object which contains the bindable property. So we need to initialize our phoneModel class
+
To make that happen we will use something known as {{Icode|DataContext}}. {{Icode|DataContext}} is the object which contains the bindable property. So we need to initialize our {{Icode|phoneModel}} class object and set it as our {{Icode|DataContext}} and then rest all will be taken care by the framework.
object and set it as our DataContext and then rest all will be taken care by the framework.
+
  
One can set the DataContext when page loads. So in MainPage.xaml.cs add an handler to page load event when page Initialization completes, inside that handler initialize PhoneModel
+
One can set the {{Icode|DataContext}} when page loads. So in MainPage.xaml.cs add an handler to page load event when page Initialization completes, inside that handler initialize {{Icode|PhoneModel}} class with some propeties and set {{Icode|PhoneModel}} object on {{Icode|DataContext}}. The C# code below will help us to understand this :
class with some propeties and set PhoneModel object on DataContext. cs code below will help us to understand this :
+
  
 
<code csharp>
 
<code csharp>
Line 139: Line 134:
 
</code>
 
</code>
  
To check what has happened we can now deploy the application on emulator and we can see the properties being binded on the TextBox attributes.
+
To check what has happened we can now deploy the application on emulator and we can see the properties being binded on the {{Icode|TextBox}} attributes.
  
 
[[File:DataBinding wp one.png|frame|none|Data Binding in Windows Phone|400x600px]]
 
[[File:DataBinding wp one.png|frame|none|Data Binding in Windows Phone|400x600px]]
Line 145: Line 140:
 
== Changing Properties and Updating UI ==
 
== Changing Properties and Updating UI ==
  
Now one can simply say if we change the properties of PhoneModel class via some events then that should also update the UI, but sadly that's not the case.
+
Now one can simply say if we change the properties of PhoneModel class via some events then that should also update the UI, but sadly that's not the case. When we are binding properties to attributes simply changing the value of the properties will not update the UI, to update the UI we need to use the simple [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] interface. We need to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] and raise an event to update the property.
When we are binding properties to attributes simply changing the value of the properties will not update the UI, to update the UI we need to use the simple  
+
[http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] interface. We need to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] and raise an event to update the property.
+
  
So first we need to change the PhoneModel class to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] Interface, now PhoneModel.cs will look like:
+
So first we need to change the {{Icode|PhoneModel}} class to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged] Interface. Now '''PhoneModel.cs''' will look like:
  
 
<code csharp>
 
<code csharp>
Line 206: Line 199:
 
     }
 
     }
 
}
 
}
 
 
</code>
 
</code>
  
The above code snippet make PhoneModel class to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged], and makes a utility method name NotifyPropertyChanged, that method raises the
+
The above code snippet make {{Icode|PhoneModel}} class to implement [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged], and makes a utility method name {{Icode|NotifyPropertyChanged}}, that method raises the {{Icode|PropertyChanged}} event with the name of the property which needs to be updated at the UI. All properties needs to call this {{Icode|NotifyPropertyChanged}} utility method.
PropertyChanged event with the name of the property which needs to be updated at the UI. All properties needs to call this NotifyPropertyChanged utility method.
+
  
To update the properties of the model and to see whether the UI get's updated or not we will add a button and on click event of the button we will change our properties and will see
+
To update the properties of the model and to see whether the UI get's updated or not we will add a button and on click event of the button we will change our properties and will see if the UI get updates or not, so the code for '''MainPage.xaml.cs''' goes like:
if the UI get updates or not, so the code for MainPage.xaml.cs goes like:
+
  
 
<code csharp>
 
<code csharp>
Line 276: Line 266:
 
== References==
 
== References==
 
* [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged]
 
* [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged]
 
+
* [http://msdn.microsoft.com/en-us/library/x9fsa0sw%28v=vs.80%29.aspx C# properties]
* [http://msdn.microsoft.com/en-us/library/x9fsa0sw%28v=vs.80%29.aspx c# properties]
+
 
+
 
* [http://msdn.microsoft.com/en-us/library/ms617928 Binding Class]
 
* [http://msdn.microsoft.com/en-us/library/ms617928 Binding Class]

Revision as of 09:23, 11 September 2012

This article explains how bind data objects in code to objects declared in your Windows Phone app's XAML UI.

WP Metro Icon File.png
WP Metro Icon UI.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone 7.1
Devices(s): Lumia 800,710
Compatibility
Platform(s): Windows Phone 7.5 (mango)
Windows Phone 8
Windows Phone 7.5
Article
Keywords: INotifyPropertyChanged
Created: gaba88 (09 Sep 2012)
Last edited: hamishwillee (11 Sep 2012)

Contents

Introduction

Windows Phone apps typically define their UI declaratively using XAML (in Expression Blend). While some UI component values may be hardcoded in XAML, many will be provided by data sources (objects, databases, XML feeds). Data binding is the technique which provides the connection between the XAML components and their values as defined in code.

This article shows how define user elements in XAML and bind their data values to an object defined in the C# file. It also shows how to use the INotifyPropertyChanged interface class to ensure that the UI is updated whenever the underlying code changes.

Getting Started

To understand binding lets create an example application for Windows Phone 7.5 and add a new class to it. New class is the model class which will contain the data properties, and will bind those data properties to UI elements in XAML file without any cs code.

namespace DataBindingEx
{
public class PhoneModel
{
public string manufacturer { get; set; }
public string model { get; set; }
public string software { get; set; }
 
}
}

PhoneModel.cs contains all the properties you want to show in your UI form, for example at present we have three textbox and they will show all the three properties declared in the PhoneModel class.

Creating the UI

Simple Windows phone page which consist of three textbox

    <!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
 
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="DataBindingExample" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
 
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="manufacturerBox" Text="manufacturer" VerticalAlignment="Top" Width="450" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="0,206,0,0" Name="modelBox" Text="model" VerticalAlignment="Top" Width="450" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="6,284,0,0" Name="softwareBox" Text="software" VerticalAlignment="Top" Width="450" />
</Grid>
</Grid>

Lets Bind Now

The above XAML code contains hard-coded data values. To bind the properties first we need to identify the attribute of the UI element which needs to be bound, then we need to use the keyword Binding in curly braces and need to specify the name of the property to which we need to bind, e.g. textbox text attribute.

We will bind with the manufacturer property of PhoneModel.cs. Now the updated XAML code looks like:

 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="manufacturerBox" Text="{Binding manufacturer}" VerticalAlignment="Top" Width="450" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="0,206,0,0" Name="modelBox" Text="{Binding model}" VerticalAlignment="Top" Width="450" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="6,284,0,0" Name="softwareBox" Text="{Binding software}" VerticalAlignment="Top" Width="450" />
</Grid>

To identify the changes please observe the text attribute of any of the TextBox in the Grid, the attribute now have binding with the manufacturer property of PhoneModel class.

Still its not clear how the XAML knows which object and its property it needs to bind, I mean to say which class the XAML should look for properties mention in the text attribute of the textbox.

To make that happen we will use something known as DataContext. DataContext is the object which contains the bindable property. So we need to initialize our phoneModel class object and set it as our DataContext and then rest all will be taken care by the framework.

One can set the DataContext when page loads. So in MainPage.xaml.cs add an handler to page load event when page Initialization completes, inside that handler initialize PhoneModel class with some propeties and set PhoneModel object on DataContext. The C# code below will help us to understand this :

namespace DataBindingEx
{
public partial class MainPage : PhoneApplicationPage
{
// declare PhoneModel object
PhoneModel _phnModel;
 
// Constructor
public MainPage()
{
InitializeComponent();
 
// add page load event handler
Loaded += MainPage_Loaded;
}
 
void MainPage_Loaded(object sender,RoutedEventArgs e)
{
// initialize _phnModel object
_phnModel = new PhoneModel
{
manufacturer = "Nokia",
model = "Lumia 920",
software = "windows phone 8"
};
 
// call utility method to set DataContext
setDataContext();
}
 
private void setDataContext()
{
ContentPanel.DataContext = _phnModel;
}
}
}

To check what has happened we can now deploy the application on emulator and we can see the properties being binded on the TextBox attributes.

Data Binding in Windows Phone

Changing Properties and Updating UI

Now one can simply say if we change the properties of PhoneModel class via some events then that should also update the UI, but sadly that's not the case. When we are binding properties to attributes simply changing the value of the properties will not update the UI, to update the UI we need to use the simple INotifyPropertyChanged interface. We need to implement INotifyPropertyChanged and raise an event to update the property.

So first we need to change the PhoneModel class to implement INotifyPropertyChanged Interface. Now PhoneModel.cs will look like:

using System.ComponentModel;
using System.Windows.Data;
 
namespace DataBindingEx
{
public class PhoneModel:INotifyPropertyChanged
{
private string _manufacturer;
private string _model;
private string _software;
 
 
public string manufacturer
{
get { return _manufacturer; }
 
set
{
_manufacturer = value;
NotifyPropertyChanged("manufacturer");
}
}
public string model
{
get { return _model; }
 
set
{
_model = value;
NotifyPropertyChanged("model");
}
}
public string software
{
get { return _software;}
set
{
_software = value;
NotifyPropertyChanged("software");
}
}
 
public event PropertyChangedEventHandler PropertyChanged;
 
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
 
}
}

The above code snippet make PhoneModel class to implement INotifyPropertyChanged, and makes a utility method name NotifyPropertyChanged, that method raises the PropertyChanged event with the name of the property which needs to be updated at the UI. All properties needs to call this NotifyPropertyChanged utility method.

To update the properties of the model and to see whether the UI get's updated or not we will add a button and on click event of the button we will change our properties and will see if the UI get updates or not, so the code for MainPage.xaml.cs goes like:

namespace DataBindingEx
{
public partial class MainPage : PhoneApplicationPage
{
PhoneModel _phnModel;
 
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
 
void MainPage_Loaded(object sender,RoutedEventArgs e)
{
 
_phnModel = new PhoneModel
{
manufacturer = "Nokia",
model = "Lumia 920",
software = "windows phone 8"
};
 
 
setDataContext();
}
 
private void setDataContext()
{
ContentPanel.DataContext = _phnModel;
}
 
// utility method which changes the PhoneModel properties
private void setPhoneProperties(String manufacturer, String model, String software)
{
_phnModel.manufacturer = manufacturer;
_phnModel.model = model;
_phnModel.software = software;
 
}
 
// called when update button is clicked
private void updateBtn_Click(object sender, RoutedEventArgs e)
{
setPhoneProperties("Nokia", "Lumia 900", "windows Phone 7.8");
}
}
}

and when you click the button the screen should look like:

Data Binding in Windows Phone


Summary

Property Binding is one of the best and simplest ways to glue your data with UI attributes.

References

674 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×