Understanding Data Binding In Windows Apps

Understanding the Data Binding allows you to build Customizable applications, and link between your data source and the presentation page. I will explain Data Binding from a different perspective that’s easy to grasp.

What’s Data Binding?!

Data Binding is an approach to link between the data you have; maybe a list of Employees, and the presentation or the view page.

Ok, What if i told you to print “Hello World” 5 times, Assuming that you know nothing about loops. Definitely you will go ahead and write the following code 5 time, one after another:

Console.WriteLine("Hello World");

What if i told you to print “Hello World” 1000 time!. It don’t think you will go and write the above code 1000 time.

So, The common solution is to use loops, where you will only write this line of code, and ask the loop statement to loop through this line of code 1000 time

for(int i=0; i<1000; i++)
Console.WriteLine("Hello World");

Or you can even better iterate over a list, that has list of names, and print them.

List<string> myList = new List<string>();
myList.Add("Joe");
myList.Add("Eddy");
myList.Add("Sara");
            for (int i = 0; i < myList.Count; i++)
Console.WriteLine(myList[i]);

So far so good? Ok, What if you have a list of Employees, and your application wants to display this list, each one has the id, name, & and salary of an employee. Probably you will say “So, we can use loops”. But, using in XAML page there is no loops, However, there are tags like GridView, and ListView.

Using GridView & ListView

Using GridView or ListView, (there are some other tags that can wrap a list of objects) we can assign their “ItemsSource” attribute to a list of Employee Objects. And it will iterate over each object and grab it’s properties.

In XAML Page,

<GridView 
x:Name="myGridList"
ItemTemplate="{StaticResource myCustomTemplate}"
HorizontalAlignment="Center">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>

Define your Custom Template for the GridView. Here you will see the term “Binding”, It says what kind of data you need to assign to Text attribute. The data is one of the object properties. This piece of code will be generated for each object in the list.

<Page.Resources>
<DataTemplate x:Key="myCustomTemplate">
<StackPanel>
<TextBlock Text="{Binding id}" Margin="5,5,5,5" />
<TextBlock Text="{Binding name}" Margin="5,5,5,5" />
<TextBlock Text="{Binding salary}" Margin="5,5,5,5" />
</StackPanel>
</DataTemplate>
</Page.Resources>

In C# Page,

Create Employee Class

public class Employee
{
public int id { get; set; }
public string name { get; set; }
public double salary { get; set; }
        public Employee(int _id, string _name, double _salary)
{
id = _id;
name = _name;
salary = _salary;
}
}

In XAML.C# Page,

Here, we will create the list, and assign it to ItemsSource attribute of GridView

private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
List<Employee> employeesList = new List<Employee>();
            employeesList.Add(new Employee(31344, "Karter", 3000.23));
employeesList.Add(new Employee(31355, "John", 6500.52));
employeesList.Add(new Employee(21277, "Kennedy", 4000.97));
            myGridList.ItemsSource = employeesList;
}

Using ObservableDictionary

There is another way to do Data Binding by using what’s called “ObservableDictionary”. It’s key-value pairs, where the value can be a String, an Object or a list of Objects.

Mostly, you will bind the ObservableDictionary to an attribute called DataContext of the Page tag. By this way it will be available for the entire xaml page.

There is an ObservableDictionary Object called “DefaultViewModel” declared by default in Basic Page Template.

In XAML Page,

Here, we are binding the DefaultViewModel to DataContext attribute inside Page Tag. “RelativeSource” It defines where we can find DefaultViewModel, It’s set to “Self”, which means, it will be in the same XAML.C# Page relevant to the current XAML Page.

DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"

You will notice here that we are binding the key “textValue” to a text block and assigning ItemsSource to the key “myList”. In the next code snippet you will set that “myList” key is assigned to the same Employee list we created before

<TextBlock Text="{Binding textValue}" Margin="15,5,15,15" />
<GridView 
x:Name="myGridList"
ItemsSource="{Binding myList}"
ItemTemplate="{StaticResource myCustomTemplate}"
HorizontalAlignment="Center">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>

In XAML.C# Page,

Here, we will create the list, and assign it to key “myList”, and also assign a string to key “textValue”.

private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
List<Employee> employeesList = new List<Employee>();
            employeesList.Add(new Employee(31344, "Karter", 3000.23));
employeesList.Add(new Employee(31355, "John", 6500.52));
employeesList.Add(new Employee(21277, "Kennedy", 4000.97));
            this.DefaultViewModel["myList"] = employeesList;
this.DefaultViewModel["textValue"] = "Welcome Page";

}

Wrapping Up

Now, you know how to display a list of anything, in addition to individual values, and bind them to the presentation or the xaml page. Here is a complete project that shows a real example combining all what we have practiced so far.

Download the code snippet, and share if you find it useful.