C# and XAML within a Silverlight 2 context - Data conversion: Part VII

In a previous article, how does C# code behind interact with an XAML interface within a Silverlight 2 context? - Data Validation: Part VI we demonstrate how to implement validation logic within a Silverlight 2 application and XAML UI and how a binding engine provides interaction between the two sides, namely the source object and the XAML UI side so that the final user will be notified when invalid entries are used. In this article I will answer the fifth question posed in the article how does C# code behind interact with an XAML interface within a Silverlight 2 context? - Introduction: Part I, which is: what if there is a need to display data in format that differs to the original one?

The solution is brought through the present article. Consider this class Person representation:

public class Person : INotifyPropertyChanged

    {

        public Person() { }

        private string _FirstName;

        public string FirstName{

            get { return _FirstName; }

            set

            {

              

                _FirstName = value;

                if (PropertyChanged != null){

                    PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));

                }

 

            }

        }

        private string _LastName;

        public string LastName

        {

            get { return _LastName; }

            set{

                _LastName = value;

                if (PropertyChanged != null){

                    PropertyChanged(this, new PropertyChangedEventArgs("LastName"));

                }

 

            }

        }

        private DateTime _BirthDate;

        public DateTime BirthDate

        {

            get { return _BirthDate; }

            set{

                _BirthDate = value;

                if (PropertyChanged != null)

                {

                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));

                }

 

            }

        }

        private string _Gender;

        public string Gender{

            get { return _Gender; }

            set{

                _Gender = value;

                if (PropertyChanged != null){

                    PropertyChanged(this, new PropertyChangedEventArgs("Gender"));

                }

 

            }

        }

        public override string ToString(){
      
     return string.Format("First name: {0},last name: {1},age: {2},gender: {3}",
                                                                                        FirstName,
                                                                                        LastName,
                                                                                         BirthDate,
                                                                                         Gender);

        }

        #region INotifyPropertyChanged Members

 

        public event PropertyChangedEventHandler PropertyChanged;

 

        #endregion

    }

Then consider this simple XAML presentation

<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  x:Class="Silverlight.Page"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Width="550" Height="50">

    <StackPanel x:Name="LayoutRoot"

                Margin="10"

                Orientation="Vertical"

                Background="White"

                >

        <TextBlock x:Name="txtPerson"

                   FontSize="12"

                   FontWeight="Bold"

                   Foreground="Black"

        Text="First name: Bejaoui,last name: Bechir ,Birth day: 11/04/78 ,gender: Male"

                   />

    </StackPanel>

</UserControl>

As we remarked the text dependency property of the txtPerson TextBlock object is already set. But what if we want to get a Person object issued from the above string that we will use in our C #program. Suppose that we have implemented a logic that stocks objects type of person within a given storage, a data base, an Xml file or so. Using a converter is the solution in that case, but the problem is that there is not standard converter to leverage our specific conversion as the Person type has been developed by ourselves, thus the System.Windows.Data namespace provides us an interface that helps to build such customized converter and this is an IValueConverter interface presentation:

public interface IValueConverter

    {

        object Convert(object value,

                       Type targetType,

                       object parameter,

                       System.Globalization.CultureInfo culture);

       

         object ConvertBack(object value,

                            Type targetType,

                            object parameter,

                            System.Globalization.CultureInfo culture);

    }

As we can remark, the both methods return an entity type of object, and they have both the same arguments set:

Type  Function
object value The initial object going to be converted
Type targetType It represents the type to which the initial type will be converted
object parameter It is used when the initial object has a parameter or the converted one has a parameter or event when there is a situation when some optional values are required for adjustement puposes
CultureInfo culture It is used when culture is going to be changed

In our situation, we need to convert an object type of Person to a certain string format and also convert this string back to the person type, so the converter will be developed as under:

public class PersonConverter : IValueConverter

    {

       

        #region IValueConverter Members

        /// <summary>

        /// This method converts a type od person object to string

        /// </summary>

        /// <param name="value">object: The initial object going to be converted</param>

        /// <param name="targetType">type: It represents the type to which the

        /// initial type will be converted</param>

        /// <param name="parameter">object: It is used when the initial object

        /// has a parameter or the converted one has a parameter or event when

        /// there is a situation when some optional values are required for

        /// adjustement puposes

        /// </param>

        /// <param name="culture">culture info: It is used when culture

        ///is going to be changed

        /// from the initial object to the final object

        /// </param>

        /// <returns>object: The returned value</returns>

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            Person person = (Person)value;

            string personToString = person.ToString();

            return personToString;

        }

        /// <summary>

        /// This method converts a type od person object to string

        /// </summary>

        /// <param name="value">object: The initial object going to be converted</param>

        /// <param name="targetType">type: It represents the type to which the

        /// initial type will be converted</param>

        /// <param name="parameter">object: It is used when the initial object

        /// has a parameter or the converted one has a parameter or event when

        /// there is a situation when some optional values are required for

        /// adjustement puposes

        /// </param>

        /// <param name="culture">culture info: It is used when culture is going to be changed

        /// from the initial object to the final object

        /// </param>

        /// <returns>object: The returned value</returns>

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            string personFromString = (string)value;

            char[] splitter = new char[] { ':', ',' };

            string[] DecomposedString = personFromString.Split(splitter);

            Person person = new Person();

            try

            {

                person.FirstName = DecomposedString[1].ToString();

                person.LastName = DecomposedString[3].ToString();

                person.BirthDate = System.Convert.ToDateTime(DecomposedString[5]);

                person.Gender = DecomposedString[7].ToString();

                return person;

            }

            catch (Exception caught) { return null; }

        }

 

        #endregion

    }

Now, we try to get the txtPerson TextBlock object in the C# code behind and get its text in order to convert it to a type of person using our customized converter as under:

TextBlock PersonDisplayer;

 public Page()

{

      InitializeComponent();

      PersonDisplayer = this.FindName("txtPerson") as TextBlock;

      PersonConverter converter = new PersonConverter();

      Person me = converter.ConvertBack(PersonDisplayer.Text, 
                    typeof(Person), 
          
          null
                     null) as Person;

            MessageBox.Show(me.FirstName);

            MessageBox.Show(me.LastName);

            MessageBox.Show(me.BirthDate.ToString("D"));

            MessageBox.Show(me.Gender);         

}

As we can remark, the string is really converted to a Person object


      
Figure 1

That's it. 

Good Dotneting!!!

Up Next
    Ebook Download
    View all
    Learn
    View all