Can you demonstrate a Simple example of OneWay and TwoWay?

 Posted by ArticlesMaint on 9/23/2009 | Category: Silverlight Interview questions | Views: 2153


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.



 


 


 


 


 


 


 


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>

 


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response