Oxygene and WP8 – Binding Data in Windows Phone

Data Binding is one of the important concept in Windows Phone 8. The Data Binding is generally done with the DataContext property which is part of the Framework Element.

Oxygene and WP8 – Binding Data in Windows Phone

For example , assume that the Object that needs to be used of Type Employee as shown below.

type
Employee = public class
  public
    property Name: System.String;
    property Designation: System.String;
end;

Now , we can create an instance of the Employee Object and assign it to the Framework element(ContentPanel in this example) of the Windows Phone Page.

ContentPanel.DataContext := new Employee(Name := 'Senthil Kumar',
Designation := 'Senior Software Engineer')

The Employee Data is now available to the items within the ContentPanel Grid . To display the data (eg : Name) , the property “Name” of the Employee Object needs to be bound to the FrameworkElement . This can be acheived via the binding markup extension and specifying the path for the binding.

For example , to bind the property Name for the TextBox , the code looks similar as shown below.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  <StackPanel>
    <TextBox Text="{Binding Path=Name}" />
  </StackPanel>
</Grid>

When you run the application in the Windows Phone device / Emulator , you should see the name displayed in the TextBlock.

Oxygene and WP8 - Binding Data in Windows Phone

The DataContext is the Source of the data received from the object . The Path refers to the Name of the property from the Object which needs to be bound to the control. Additionally , the Binding markup extension also includes an attribute mode which includes the values OneTime , OneWay and TwoWay.

Download the sourcecode used in the above example here

You can also bind the object from code behind. The Steps to bind the data using Oxygene / Code behind requires the Binding Object to interact between the FrameworkElement and the Object (Employee in this example). Once the Binding Object is created , it needs to be set to the TextBox via the SetBinding method as shown below.

var emp: Employee := new Employee(Name := 'Senthil Kumar',
Designation := 'Senior Software Engineer'
);
var binding: System.Windows.Data.Binding := new System.Windows.Data.Binding(Source := emp,
Path := new PropertyPath('Name'),
Mode := System.Windows.Data.BindingMode.OneWay);
txtName.SetBinding(TextBox.TextProperty, binding)

The XAML code for the TextBox is as shown below.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  <StackPanel>
    <TextBox Name="txtName" />
  </StackPanel>
</Grid>

Download the sample Code Snippet for binding the data from code behind here

Leave a Reply