In Part 3 of this little mini-series on data binding in Windows 8 we looked at Element Binding. Today, we’ll take a look at Data Conversion.
At times the data in your business object (the source for your binding) and the target UIElement may not have an exact type match. For example, if your Employee class wants to keep track of the start date for each Employee, a sensible way to do so is with a DateTime object. However, when we display that data we’ll want to use a Text object, and we may not want the entire default conversion of a DateTime to a string. To rectify this problem, we can create a class that performs a conversion from one type to another (in this case, from DateTime to string). This class will implement IValueConverter and will have two methods: Convert, and ConvertBack.
Here’s our modified Employee class,
We now need a new class that implements the IValueConverter interface,
Notice the new use of formatting in date.ToString. See this MSDN article.
We can now create a resource for this converter class in the XAML,
This allows us to use that resource when we bind to StartDate,
As a result, the StartDate property is a DateTime object in the Employee object, but it is represented as a short string in the UI.
Remember to update the Employee constructor to take three arguments,
and initialize the new Employee object in the code behind,
protected override void OnNavigatedTo(NavigationEventArgs e)
emp = new Employee( "Joe", "QA", new DateTime(2012,7,10) );
xDisplay.DataContext = emp;
The result, in this case, is just to display the start date for this employee, formatted as we wanted.
Jesse Liberty has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and has been a Distinguished Software Engineer for AT&T and a VP for Information Services for Citibank and a Software Architect for PBS. You can read more on his personal blog or follow him on twitter
Subscribe to be the first to get our expert-written articles and tutorials for developers!