×
Namespaces

Variants
Actions
(Difference between revisions)

Data Binding to controls on Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
pooja_1650 (Talk | contribs)
(Pooja 1650 -)
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Fix metadata)
Line 6: Line 6:
  
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= [[Media:DataBindingEx.zip]]  
+
|sourcecode= [[Media:DataBindingEx.zip]]
|devices= Lumia 800,710  
+
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 +
|devices= Lumia 800,710
 
|sdk= Windows Phone 7.1
 
|sdk= Windows Phone 7.1
 
|platform= Windows Phone 7.5 (mango)
 
|platform= Windows Phone 7.5 (mango)
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|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= C# Properties, [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx INotifyPropertyChanged]
 
|keywords= C# Properties, [http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx 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]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
Line 32: Line 33:
  
 
== 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.1 O/S 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.
  
Line 142: Line 143:
 
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 TextBox attributes.
  
[[File:DataBinding_wp_one.png|frame|none|Data Binding in Windows Phone]]
+
[[File:DataBinding wp one.png|frame|none|Data Binding in Windows Phone]]
  
 
== 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  
+
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.
 
[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.
  
Line 269: Line 270:
 
and when you click the button the screen should look like:
 
and when you click the button the screen should look like:
  
[[File:DataBinding_wp_two.png|frame|none|Data Binding in Windows Phone]]
+
[[File:DataBinding wp two.png|frame|none|Data Binding in Windows Phone]]
  
  

Revision as of 10:35, 10 September 2012

This article explains how to bind data to your windows phone application. Article shows how to bind data in XAML files and later on also explains how to update data in UI components using INotifyPropertyChanged interface class.


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: C# Properties, INotifyPropertyChanged
Created: gaba88 (09 Sep 2012)
Last edited: hamishwillee (10 Sep 2012)

Contents

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 manipulation and navigation.

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 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 binded, 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. cs 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.

×