Data Binding In UWP Apps

Data Binding is one of the most interesting topic in Universal App Development. In order to perform  better functionality, you really need to have some great usage of Data Binding in you apps.

So! First thing first. What is Data Binding and is its usage in UWP. Don’t worry, Data Binding is not a Rocket Science. It’s just a way to establish a connection between App UI and its Business Logic. Normally we use the terminology Binding which is known as Data Binding. Very common Dev word.

As in the modern apps, the Three-Tier Architecture Model is commonly used which is the fundamental framework for the logical design model, segments an application's components into three tiers of services. These three tier architecture correspond to logical layers of the App.

The three tiers include: Presentation Tier or User Services Layer, that presents data to the user and optionally permits data manipulation and data entry. Middle Tier or Business Logic Layer, that contains all the business logic of the App. Data Ties or Data Service, that interacts with persistent data usually stored in a database or in permanent storage. This can be accessed through the business layer.

During the App life cycle, this three-tier approach provides great benefits such as reusability, flexibility, manageability, maintainability, and scalability. You can share and reuse the components and services you create, and you can distribute them across a network of computers as needed. You can divide large and complex projects into simpler projects and assign them to different programmers or programming teams. You can also deploy components and services on a server to help keep up with changes, and you can redeploy them as growth of the applications user base, data, and transaction volume increases. And further there’re lot of other benefits.

In Data Binding, basically we are tying the Presentation Layer with the Business Layer/Data Model of an Application.

You can declaratively define the data source (most likely a collection of objects) in Data Later for a given control (let say, a grid or a list) in Presentation Layer and then tell the control to bind to the data source. It then takes care of creating a visual representation of each item in the data source as a row, a list item, etc...

When building UWP apps in XAML, you use the Binding syntax with XAML+UWP.

Let’s do some hands-on and see how can you bind to a static resource for the purpose of styling.

Simply start by creating a new Blank App project template named SimpleDataBinding in Microsoft Visual Studio 2015,

Image

Now simply draw TextBlock and a Button control over the Design Surface to retrieve and display values input in the controls we’ll learn about. This will demonstrate how to retrieve values from these controls programmatically in C#.

Image

We can use a TextBlock and a Button control to retrieve and display values input in the controls we’ll learn about. This will demonstrate how to retrieve values from these controls programmatically in C#.

So, let’s add a definition for a TextBox,

textbox

Here TextBox will allow a user to type in text using an on-screen keyboard. The key to this example is the InputScope=”TelephoneNumber”. As we’ll see in a moment, changing the InputScope changes the types of information (or rather, the keyboard) that is displayed to the user.

Note that myButton’s Click event is handled. We’ll need to create an event handler method stub. To do this, I’ll right-click the value “myButton_Click” and select “Go To Definition” from the context menu:

def

That will magically create a method stub in the MainPage.xaml.cs code behind

MainPage

Now here we’ll retrieve the number typed into the myTextBox and display it in the myTextBlock;

myTextBlock

Now basically here we’re binding the data. Now if you run the application and see. Whatever you’ll type TextBox then click upon Button that will be shown in the TextBlox. That is because in the event handler we’re binding the data of TextBox with TextBlock.

Image

There are many different InputScope keyboard available. In the XAML editor, I can rely on IntelliSense to help me see the possible enumerated values:

Intellisense

In this case, I’ll change the InputScope=”Url”.

InputScope

And this time when I run the app, I can see that I have a keyboard that is geared towards helping me type in URLs (note the .com key near the space bar at the bottom).

Now let’s have a look at the ComboBox which will allow us to display multiple possible options as a series of ComboBoxItems,

ComboBoxItems

In order to retrieve the selected ComboBoxItem, we’ll add the following code to my myButton_Click event handler,

myButton_Click

Also, to provide an initially selected / default value, I’ll set the IsSelected=”True” attribute value:

IsSelected

And when we run the app, notice that the ComboBox is already set to “Second Item”:

Image

Isn’t it great!

And when we click on that item, a list control appears displaying all the possible items in the ComboBox. We can select one of them and click the checkmark icon in the command bar to accept that choice,

Image

Now let’s look at the CheckBox. It is useful when you want to retrieve a yes or no answer from the user:

CheckBox

In order to retrieve the value from the CheckBox, we’ll use the IsChecked property. Here, I use the decision operator to return one of two strings depending on whether IsChecked is true or false,

CheckBox1

Now if we run the app and check the CheckBox, then click the Button, we can see the value returned in each “state” of the CheckBox;

Image

Similar to the CheckBox is the RadioButton. The only difference: RadioButton work in groups so that no two RadioButton in a group can be selected at the same time. This is useful where you want to present a limited set of options to the user (otherwise you should use the ComboBox). Here I create two RadioButton:

RadioButton

Here in logic we can determine which RadioButton was checked:

RadioButton

Now when we run the app, we can see my selection and the associated text when we choose a RadioButton. After that click the button,

Image

Now let’s do another move. Add a few more RadioButtons;

RadioButtons

Now we’ve total buttons. They all are in the same group.

Image

So let’s split these four RadioButtons into two separate groups. Let’s give the last two RadioButton controls a GroupName. The  GroupName must be spelled the same in order for them to be grouped together,

group

It is important to add GroupName to RadioButtons, otherwise they will be added to a default group.

Now when you run the app, we have two groups of RadioButtons, each group allowing a selection of a single RadioButton:

Image

Now lets play with DatePicker with Binding which allows the user to enter a reliable date using a special flyout;

DatePicker

To retrieve the selected date from the DatePicker, add the following code in logical file:

Image

When you run the app and tap the DatePicker, a flyout displays a three-column selection control. You can change the month, day and year independently by scrolling the date part up or down. Once I’ve found the date I’m looking for, I select the check mark icon to accept the selection or the x icon to cancel:

Image

You could use the many built-in DateTime formatting options on this string before you display it or you could use String.Format special formatting codes,

Image

Now let’s play with the TimePicker. This is almost identical to the DatePicker except it only deals with the Time part:

TimePicker

In order to retrieve the current selected Time from the TimePicker and display it in the TextBlock,

TimePicker

Now when you run the app, you will get a cool TimePicker,

Image

Just like DateTime you could use the many built-in DateTime formatting options on this string before you display it or you could use String. Format special formatting codes,

Image

Now let’s play with the Slider control which allows a user to choose a value between a Minimum and Maximum value. In this case, the Minimum will be 0 (the default) and the Maximum will be 100.

slider

When you run the app, you can drag the slider to the right (higher value) or to the left (lower value);

The Slider simplifies numerical input as long as there’s only a limited set of values and precision is not important.

Image

Now let’s do some binding with Slider. Add a TextBlock and bind its Text with Slider Value,

Image

Now when you run the app. You’ll see the value of TextBlock will change as you change the ScrollBar position,

Image

Now similarly insert demonstrate the use of a ProgressBar . You typically use a ProgressBar to display feedback to the end user as to the progression of a given operation. As the bar creeps from left to right, it lets the user know the approximate progress and pace of the operation.

In our case, we’ll use the ProgressBar to mirror the current value of the Slider control. In other words, as you drag the Slider left and right, we’ll retrieve the value of the Slider and set it to the value of the ProgressBar. We’ll use a binding to do that. Here, we’ll set the Value attribute of the ProgressBar to the Value of the mySlider control using a special binding syntax,

ProgressBar

Now when you will run the app, as you change the value of the Slider, the ProgressBar and TextBlock value change as well.

Image

Similar to the ProgressBar is the ProgressRing. While the ProgressBar provides feedback as to the estimated completion of a given task, the ProgressRing only provides feedback to the user that the operation is in progress with no indication how long until completion. We’ll add the ProgressRing’s XAML to our MainPage.xaml:

ProgressRing

And pair this control up with another common control, the ToggleButton. The ToggleButton has three states: On, Off and Unknown. First, we’ll add the ToggleButton:

ToggleButton

If you want to respond each time the user taps the ToggleButton, simply handle the Click event. Once again, right-click the event handler method name “myToggleButton_Click” and select “Go To Definition” from the context menu,

myToggleButton

To create a method stub inside the method, I’ll add the following code:

stub

Based on the IsChecked property of the ToggleButton, simply set the ProgressRing’s IsActive property to true (turns it on) or false (turns it off). When you run the app and click the ToggleButton to the On state, the ring pulsates:

Image

Now let's play with TextBox by binding one TextBox with another,

Image

And when you’ll run the app, because the second TextBox bind with first TextBox, whatever you type in Second TextBox will be shown in first TextBlock,

Image

See, how cool is that.

These are some of the very most common controls. Some of them like our DatePicker, TimePicker, the ComboBox employ other controls like the Flyout that will display other options on another “page” and when you make the selection, it will return to the original page with the given control set to the selection the user made.

There are literally hundreds of additional properties, dozens for each of the controls that are displayed here for specific purpose.

For further deep dive, take a view over the list of properties for a given control to get an idea of what it can do. And whenever you come across a property you do not understand, take a moment and search MSDN for more information to see if it can help you accomplish what you need.

When building UWP Apps, you use the Binding syntax as we play above with different objects. We played how to bind to a static resource for the purpose of styling.

So, you bind to data in a similar way using a similar syntax.

<TextBlock Text="{Binding Title}" … />

At the most fundamental level, binding is simply a mechanism for updating one property from another. Rather than writing the code (Or doing hardcode that code) to push the date from the source to the target that binding framework does the job,

Image

So here’s an example of Binding in an XAML file;

Image

In the first line of above code, We’ve a textblock. That is serving as the binding target. On Text Line we’re specifying the text property as the binding data property. At runtime this text property is set by the Binding Framework. The curly braces indicated that we’re using the markup extension. i.e. it is a class that invoke at run time to do some work. This above case is that it invoke to do some binding work. We chose our data source with element name property in the binding. And we indicate that we want the data to come from the text box, named TextBox1. We also indicate which property will supply the data, the Text Property.

So we’re taking Text as the source and applying to the text in the target. And on text line we define the source of the data. A UI element name ‘TextBox1’.

It is also possible to bind a Non-UI element. In next two lines of above code, we have a TextBlock binding to a Business class.

Data can flow from Source into the Target property, it can do this continuously every time there’s some update in the source, the target gets the updates. That is ‘One Way’ Binding.

Alternatively, you can bind the data as ‘One Time’, which only updates the Target once. No matter how much the underline data changes. There’s also a ‘Two-Way’ binding. Which means let say, updates back to the source. The TextBox uses the two way binding by default.

The Binding Framework is well suited for setting the data on the target. The framework cannot provide continues updates to the target unless source implements the contain rules. For example,

For User Controls and UI Elements, if you want its property under control by updateable source, it must be written in the dependency property.

For Business Classes, you must have to implement the INotifyPropertyChanged Interface in the class.

Sometime the data is stored in Updateable collection. Usually data shown in the list control of the source.

Binding Framework cannot provide update from collection source unless; Create a class that implements INotifyCollectionChanged Interface but the easiest and recommended way to handle it by using ObservableCollection<T> as collection type.

Sometimes the data is not in the correct format or shape desired the binding target. E.g. you’ve numeric data in the source, you can write a value converter to change the numeric value into Red Solid Color Brush. This converter is called whenever the data is updated to the target. BTW the converters are bidirectional, so the converter can modify the data as it has back to be data source from the target.

In simple words, if you want to display some words on the screen or some content on the button you can hardcode that code directly in the XAML,

Image

Image

But the problems will be that it is difficult to change, you can’t bind it with the data inside the app. So it’s very static way to doing things. And it will be not dynamic, that you run it and change,

Image

Image

Whatever object, the data context applying or pointing to the element or a container element we look at the property of that object and pull that out from Data Source or View Model and put it over the View layer or at the screen. And it doesn’t matter with Data Source that where it is consumed. Here, the UI is like an observer of the presenter. The View Model Classes are representing that, whoever wants to consume it. But UI needs to know whatever it changes. That’s why we can use; INotifyPropertyChanged; Implement in a view model class & raised by View Model when property value changes and INotifyCollectionChanged; Implemented in ObservableCollection<T> and ReadOnlyObservableCollection<T> Raised by the collection when the collection is modified (also IObservableVector).

So that was a simple example of Classic Data Binding.

Let’s play and do some Element to Element Binding,

Image

See, we simply create two TextBox and bind the SourceTB Text in TargetTB Text. Now if you run the app,

Image

But if we try to modify the Text from the Target then it only change in Target,

Image

That is because we’ve done One Way Binding. The Data is bind only one way so when we change data from other side it will only be affected on that side.

Now, if you want to make it two-way data binding. i.e. whether you change on source or target, both sides will see that change.

Let’s do this by another way. Simply select the TextBox which we’re going to bind and go to properties and in Common Property, go to Text and on click upon the Black Rectangle go to Create Data Binding;

Image

And simply select the Binding Type as  ElementName and bind the SourceTB with Text: (String) in path. Moreover, from Fewer settings, select the Binding Direction as TwoWay;

Image

You’ll see, Visual Studio will smartly create code for you,

Image

And now when you’ll run the application. You’ll see that two-way binding will occur.

Here’s another example of element to element binding. The TextBox is bound with TextBlock and it is bound in such a way that Text.Length visible in TextBox.

Image

When you run the App how many characters you’re typing will be shown in TextBox;

Image

See, how cool is it.

Now let’s play another trick and change the size of a text icon based upon movement of a slider,

Image

Now when you move the slider, you’ll see the size of the text image will also change,

Image

You can see how interesting it is to play with Data Binding. You can use Data Binding tricks in your app in different domains and make your apps smart and cool.

For Demo

In order to get a best hands-on experience along with the Blog. Try out the code either By MSDN Code Samples or By GitHub .


Similar Articles