Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » One way, two way and one time bindings using Silverlight

One way, two way and one time bindings using Silverlight

This article will talk about three ways of binding object properties with Silverlight user interfaces. We will first go through the fundamentals of the 3 bindings and then take up a small sample which will demonstrate how the binding works.

Author Rank:
Technologies: .NET 3.0 and 3.5, Silverlight,Visual C# .NET
Total downloads : 139
Total page views :  17399
Rating :
 4.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverLightBinding.zip
 
Become a Sponsor




Introduction

This article will talk about three ways of binding object properties with SilverLight user interfaces.  We will first go through the fundamentals of the 3 bindings and then take up a small sample which will demonstrate how the binding works. We have also attached the source for the same.

Other Silverlight FAQ

In case you are a complete fresher to silverlight then below are some silverlight FAQ's  which can give you a quick start in this topic.

Silverlight FAQ Part 1:- For article click here  This tutorial has 21 basic FAQ's which will help you understand WPF, XAML, help your build your first silverlight application and also explains the overall silverlight architecture.

SilverLight FAQ Part 2 (Animations and Transformations):- For article click here This tutorial has 10 FAQ questions which starts with silverlight animation fundamentals and then shows a simple animated rectangle. The article then moves ahead and talks about 4 different ways of transforming the objects. 

One way bindings

As the name so the behavior. In one way bindings data flows only from object to UI and not vice-versa. For instance you can have a textbox called as 'TxtYear' which is binded with an object having property 'Year'. So when the object value changes it will be reflected on the silverlight UI, but the UI cannot update the year property in the object.

1.JPG
 










It is a three step procedure to implement one way binding. First create your class which you want to bind with the silverlight UI.  For instance below is a simple class called as 'ClsDate' with a 'Year' property.

public class clsDate
{
    private int _intYear;
    public int Year
    {
        set
        {
            _intYear = value;
        }
        get
        {
            return _intYear;
        }
    }

}

In the second step you need to tie up the 'Year' property with a silver light UI text box. To bind the property you need to specify 'Binding Path=Year' in the text property of the text box UI object. 'Year' is the property which we are binding with the text box UI object.

<TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

The final step is to bind the text box data context with the date object just created.

public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
        clsDate objDate = new clsDate();
        objDate.Year = DateTime.Now.Year;
        txtCurrentYear.DataContext = objDate;
    }

}
 

Two way binding

Two way binding ensure data synchronization of data between UI and Objects. So any change in object is reflected to the UI and any change in UI is reflected in the object.

2.JPG
To implement two way binding there are two extra steps with addition to the steps provided for 'OneWay'. The first change is we need to specify the mode as 'TwoWay' as shown in the below XAML code snippet.

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

Second change is we need to implement 'INotifyPropertyChanged' interface. Below is the class which shows how to implement the 'INotifyPropertyChanged' interface. Please note you need to import 'System.ComponentModel' namespace.

public class clsDate : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _intYear;
    public int Year
    {
        set
        {
            _intYear = value;
            OnPropertyChanged("Year");
        }
        get
        {
            return _intYear;
        }
    }
    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(property));
        }
    }

}

The binding of data with data context is a compulsory step which needs to be performed.

One time binding

In one time binding data flows from object to the UI only once. There is no tracking mechanism to update data on either side. One time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.  

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=OneTime}" Height="30" Width="150"
 VerticalAlignment
="Center" HorizontalAlignment="Center"></TextBox>

Simple demonstration of OneWay and TwoWay

Below is a simple sample code where in we have two text boxes one takes in the age and the other text box calculates the approximate birth date.

3.JPG

Below is a simple class which has both the properties. We have implemented 'INotifyPropertyChanged' interface so that we can have two way communication for the year property.

using System;
using
System.Net;
using
System.Windows;
using
System.Windows.Controls;
using
System.Windows.Documents;
using
System.Windows.Ink;
using
System.Windows.Input;
using
System.Windows.Media;
using
System.Windows.Media.Animation;
using
System.Windows.Shapes;
using System.ComponentModel;
namespace
SilverLightBinding
{
    public class clsDate : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private int _intYear;
        private int _intAge;
        public int Year
        {
            set
            {
                _intYear = value;
                OnPropertyChanged("Year");
            }
            get
            {
                return _intYear;
            }
        }
        public int Age
        {
            set
            {
                _intAge = value;
                Year = DateTime.Now.Year - _intAge;
            }
            get
            {
                return _intAge;
            }
        }
        private void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                      new PropertyChangedEventArgs(property));
            }
        }
    }
}

Finally we have also binded the SilverLight UI objects with the class properties.  Below is the XAML snippet for the same. One point to be noted is that 'Age' is bounded using two way mode as we need to modify the same from the user interface.

<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Enter your age in the below text box</TextBlock>
<
TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>
<
TextBlock VerticalAlignment="Center" HorizontalAlignment="Center">Your approximate birth date</TextBlock>
<
TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

At the top of this article you can get the Source Code.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverLightBinding.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved