A Place For My Thoughts, Analytical Activities & Research

JUMPSTART WITH DATA BINDING IN UWP

by

Data Binding is one of the most interesting topics in Universal App Development. In order to perform the better functionality, you really need to have some great usage of Data Binding in you Apps.
So! First thing first. What is actually the 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 World.
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 tiers 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 the growth of the application’s user base, data, and transaction volume increases. And further, there’re a lot of other benefits.
So! In Data Binding, basically, we are trying 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;
1download
Now Simply draw TextBlock and a Button control over the Design Surface to retrieve and display values inputted in the controls we’ll learn about. This will demonstrate how to retrieve values from these controls programmatically in C#.
download (1)
We can use a TextBlock and a Button control to retrieve and display values inputted 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 as follows;
1ResReader
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:
ResReader (1)
That will magically create a method stub in the MainPage.xaml.cs code behind;
ResReader (10)
Now here we’ll retrieve the number typed into the myTextBox and display it in the myTextBlock;
ResReader (3)
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.
download (2)
There are many different InputScope keyboard available. In the XAML editor, I can rely on Intellisense to help me see the possible enumerated values:
ResReader (4)
In this case, I’ll change the InputScope=”Url”…
ResReader (5)
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;
ResReader (6)
In order to retrieve the selected ComboBoxItem, we’ll add the following code to my myButton_Click event handler;
ResReader (7)
Also, to provide an initially selected / default value, I’ll set the IsSelected=”True” attribute value:
ResReader (8)
And when we run the app, notice that the ComboBox is already set to “Second Item”:
download (3)
Hahaha… 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 on of them and click the checkmark icon in the command bar to accept that choice;
download (4)
Now Let’s look at the CheckBox. It is useful when you want to retrieve a yes or no answer from the user:
ResReader (9)
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;
ResReader (10)
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;
download (5)
Similar to the CheckBox is the RadioButton. The only difference: RadioButtons work in groups so that no two RadioButtons 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 RadioButtons:
ResReader (11)
Here in logic we can determine which RadioButton was checked:
ResReader (12)
Now When we run the app, we can see my selection and the associated text when we choose a RadioButton then click the Button;
download (6)
Now let’s do another move. Add a few more RadioButtons;
ResReader (13)
Now we’ve total buttons. They all are in the same group.
download (7)
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:
ResReader (14)
It is important to add GrroupName 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:
download (8)
Now let’s play with DatePicker with Binding which allows the user to enter a reliable date using a special flyout;
ResReader (15)
To retrieve the selected date from the DatePicker, add the following code in logical file:
download (9)
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:
download (10)
You could use the many built-in DateTime formatting options on this string before you display it or you could use String.Format’s special formatting codes;
download (11)
Now let’s play with the TimePicker. This is almost identical to the DatePicker except it only deals with the Time part:
ResReader (16)
In order to retrieve the current selected Time from the TimePicker and display it in the TextBlock;
ResReader (17)
Now when you run the app, you will get a cool TimePicker;
download (12)
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’s special formatting codes;
download (13)
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.
ResReader (18)
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.
download (14)
Now let’s do some binding with Slider. Add a TextBlock and Bind its Text with Slider Value;
download (15)
Now when you run the app. You’ll see the value of TextBlock will change as you change the ScrollBar position;
download (16)
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:
Untitled
Now when you will run the app as you change the value of the Slider, the ProgressBar’s and TextBlock value changes as well.
download (17)
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:
ResReader (20)
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:
ResReader (21)
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:
ResReader (22)
To create a method stub. Inside the method, I’ll add the following code:
 
ResReader (23)
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:
download (18)
Now Let’s play with TextBox by binding one TextBox with another;
download (19)
And when you’ll run the app because the second TextBox is Bind with the first TextBox; whatever you type in Second TextBox will be shown in First TextBlox;
download (20)
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 the 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…
So! 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 having write the code (Or doing hardcode that code) to push the date from the source to the target that binding framework does the job;
download (21)
So here’s an example of Binding in a XAML file;
Untitled

On First line of above code, We have a text block. 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’s a Class that invokes at runtime to do some work. This above case its 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 TexBox1. 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 very text line we define the source of the data. A UI element name ‘TextBox1’.
It’s also possible to bind a Non-UI element. In next two lines of above code, we show 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 says, 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.
Sometimes the data is stored in Updateable collection. Usually, that data are shown in the list control of the source.
Binding Framework cannot provide the update from collection source unless; Create a class the implements INotifyCollectionChanged interface but the easiest and recommended way to handled 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 bi-directional, so the converter can modify the data as it has back to be the 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;
download (23)
download (24)
But they problems will be that it difficult to change, you can’t bind it to the data inside the app. So it’s very static way of doing things. And it will not dynamic, that you run it and change it;
download (25)
download (26)
That is saying is 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 on the screen. And Its 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’s, whoever wants to consume it. But UI needs to know whatever is 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 the simple example of Classic Data Binding.
Let’s play and do some Element to Element Binding;
download (27)
See, we simply create two TextBox and bind the SourceTB Text in TargetTB Text. Now If you run the App;
download (28)
But if try to modify the Text from the Target then it only changes in Target;
download (29)
That is because we’ve done One Way Binding! The Data is bind only one way so when we change Data from another side it will only be affected on that side…
Now, if you want to make it two-way data binding. i.e. weather you change on source or target, both sides will see that change…
But 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 in click upon the Black Rectangle and go to Create Data Binding;
download (30)
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;
download (31)
You’ll see, Visual Studio will smartly create code for you;
download (32)
And now when you’ll run the application. You’ll see that two-way binding will be occurring…
Here’s another example of the element to element binding. The TextBox is Bound with TextBlock and it is bound in such a way that Text.Length shows in TextBox.
download (33)
So When you run the App. How many characters you’re typing will be shown in TextBox;
download (34)
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;
download (35)
Now when you move the slider, you’ll see the size of the text image will also change;
download (36)
So! You See! How interesting is it 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 HANDS ON 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.

Data Scientist & Solution Architect || IBM Recognised Speaker, Mentor, and Teacher || Debater || Blogger || Guinness World Record Holder || Watson Solution Developer || IBM Community Activist || Aspiring to Inspire.

Leave a Reply

Your email address will not be published.

*

Latest from Development

JumpStart with DevOps

What is DevOps; DevOps is a Software Development Strategy, that bridges the
Go to Top
Close Bitnami banner
Bitnami