Monday, June 28, 2010

Implementation of IValueConverter Interface.

I have done small experiment on IvalueConverter in Silverlight.
So,I am presenting here my small experiment.


I am giving a small sample code for IvalueConvert interface and how can we implement in binding(XAML).

Suppose, I want to convert/format date time in side a datagrid or in textbox while binding.
Todo this we have to follow three steps.

Step 1: Create a class , (here I am giving name it as DateConverter.) and implement interface IvalueConverter.


public class DateConverter : IValueConverter
    {
        public object Convert(object value,
                              Type targetType,
                              object parameter,
                              System.Globalization.CultureInfo culture)
        {
DateTime date = (DateTime)value;
            return date.ToString(parameter.ToString());
        }
public object ConvertBack(object value,
                                  Type targetType,
                                  object parameter,
                                  System.Globalization.CultureInfo culture)
        {
            string strValue = value.ToString();
            DateTime resultDateTime;
            if (DateTime.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return value;
        }
}

these two methods( Convert & ConvertBack) will take four parameters.

Step 2: Add class reference to XAML.

  xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:c="clr-namespace:SilverlightApplication6"
    Width="400" Height="300">
   
        //Adding name space of class reference.
   

   
  
                     
   




Step 3: Binding data to textblock using InotyfypropertyChanged.
public class Customer : INotifyPropertyChanged
    {
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private DateTime _birthday;
public DateTime Birthday
        {
            get { return _birthday; }
            set
            {
                _birthday = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Birthday"));
                }
            }
        }

}
.


aravindbenator@gmail.com

No comments:

Post a Comment