Friday, February 15, 2013

Run-time Data Binding

Category: Windows Store App Developing
Prerequisites: XAML, C++, C++/CX, Simple Data Binding

Data binding lets you synchronise UI control elements in XAML with data source that can be dataset, data object or any primitive data types. Usually you just set binding property for any UI control elements and then set BindableAttribute attribute for the ref class in the code behind. And when you compile your code, the compiler will do the rest and all properties in your class will be bindable.

The Problem
Sometimes you may need data class that uses dynamic properties. That means you don’t know at compile time what and how many data properties and types the class should have. This is a common situation such as when you retrieve data set from the SQL server that you usually specify data fields at run time. In these cases, BindableAttribute attribute doesn't help.

The Solution
My solution is to implement ICustomPropertyProvider for the ref class. In this article I call this technique as Run-time Data Binding. The steps are as follows:

1. First, create new ref class with inheriting and implementing ICustomProperty. This class will be used for representing run-time property you will create later.

2. Create another new ref class with inheriting and implementing ICustomPropertyProvider. If you want to be notified when your property changed you can also inherit and implement INotifyPropertyChanged here. Don't forget to inherit from DependencyObject, this is mandatory.


In this class I used Map Collection to store my CustomProperty objects and created two public methods for getting and setting value for CustomProperty target.


Now you will have two ref class that can be used for run-time data binding.

3. Create new ref class to be used for run-time binding which inherit from CustomPropertyProvider ref class. In this case I'll create Person Class that will have name property created at run-time.


4. Insert name property at rum-time.