(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Getting ready for Microsoft Silverlight Exam 70-506 (Part 4)

(7 votes)
Gill Cleeren
>
Gill Cleeren
Joined Apr 02, 2010
Articles:   63
Comments:   6
More Articles
0 comments   /   posted on Feb 07, 2011
Categories:   Data Binding , Data Access , General
SilverlightShow and Gill Cleeren start a series of materials aimed at helping you get prepared for taking Microsoft Silverlight Exam 70-506. Through this series we will try to structure the resources available on the internet, grouping them by topic covered in the exam. Any feedback would be much appreciated! Thanks! 

This article is Part 4 of the series on Microsoft Silverlight Exam.

We are making great progress in our Silverlight Exam series, we are now in the fourth part already. A quick look back on the previous parts shows that we started with a deep look at the layout and UI-related material. In the second part, we looked at enhancing the UI using features such as the Visual State Manager. In the previous part, the focus was mainly on the coding part, including topics such as dependency properties, the ICommand interface and working asynchronously with services.

This fourth part will focus on a very important aspect: data. Not a single business application works without data and since one of the focus areas of Silverlight of LOB development, Silverlight is well-equipped to handle data. In this part, we’ll look at data binding, which is something you have to understand deeply. The data binding system is very powerful and enables the MVVM pattern. When working with data (mainly the input process), data needs to be validated as well. Silverlight 4 brings some new options, enabling a much cleaner way to perform validation on inputted data.

For your convenience, the following list contains links to the other parts of the article series which have been finished already:

Part 4: Working with data

As mentioned in the intro, many developers are using Silverlight to build business applications. And of course, business apps need to work with data: displaying data, accepting data input, validating input etc. While all this is very well possible to code manually (using code that looks like MyTextBlock.Text = person.FirstName), it’s prone to errors and gets tedious to write quickly. It’s certainly not the most exciting code to write, I think you’ll agree with me on that.

Introducing data binding. It’s easily the most important topic to really grasp when learning Silverlight. The concept of data binding basically comes down to a construct that allows binding – or linking – properties of controls to properties of objects. Instead of having to write all that code manually however, the data binding engine takes a lot of the load out of our hands and lets us create binding from XAML. The data binding engine found in Silverlight is brought in from WPF. WPF’s version has still some more options, but the difference is getting smaller with every new release of Silverlight. Conceptually, data binding is nothing really new. We can do data binding in ASP.NET or WinForms as well; however the model in Silverlight (and WPF of course) is much more loosely coupled.

Not only is data binding important to build data-driven applications, it’s also the concept that makes MVVM (Model-View-ViewModel) possible. If you know your way around the pattern, you’ll quite easily understand that the View is bound to an instance of the ViewModel (in other words, an instance of the ViewModel is set as the DataContext for the View). The ViewModel exposes properties and commands to which the elements in the View can bind. For example, a List<T> exposed on the ViewModel can be the source for a data binding on the View. Commands (which we explored in part 3) are exposed as public properties as well and using the Command property on some controls (in Silverlight 4 only on ButtonBase and controls driving from ButtonBase), we can bind an action in the ViewModel to an event in the View. As you’ll understand, the MVVM pattern really builds on the concepts introduced by data binding.

Implement data binding

In this section, we’ll look at all concepts that are linked to data binding. Many of these are closely related, so you’ll learn about them in one go I assume.

I did a webinar with SilverlightShow where we look at many data binding topics. You can watch it on-demand from here: http://www.silverlightshow.net/shows/SilverlightShow-Webinar-Data-Binding-in-Action-by-Gill-Cleeren.aspx

If you want to read more on data binding itself, take a look at the following links:

  • Data binding explained on MSDN: http://msdn.microsoft.com/en-us/library/cc278072(v=vs.95).aspx
  • http://www.silverlight.net/learn/tutorials/silverlight-4/silverlight-data-binding/
  • http://www.singingeels.com/Articles/Silverlight_DataBinding_Basics.aspx

In the following links and topics, we’ll look at some specifics from data binding:

  • Setting the data context
    We all know that XAML is a hierarchy. The concept of the data context is built on this. Let me explain.
    When creating a simple data entry form (for example to gather person data), we can use data binding. All the TextBox instances where data can be entered need to know to which property on a bound object (a Person instance) they are bound. We could do this by specifying on each TextBox the name of the property. While this is possible, it would actually be a lot of work and would perhaps take away some of the benefit we get from using data binding.
    The DataContext allows us to define a common source on a higher level in the XAML tree. So, assume all the TextBox instances are children of a Grid, we can set the DataContext of the Grid to be the Person object. When no source is defined on the binding expression, the data binding engine will start searching (using a process referred to as XAML tree walking) up the XAML tree to find a non-null data context. Once found, the object is used as the source for the binding.
    The DataContext is often used in MVVM to set a ViewModel instance as the source for the View.
  • Binding data sets to controls
    Next to binding a single object to form, we often want to bind a list of items to a list control such as a ListBox. Silverlight’s data binding engine is perfectly capable of this as well. The ItemsSource property on these controls is our friend here and be used for this exact purpose. By default however, we won’t get a good visual representation of the bound data: an item will be shown using its ToString() implementation. That’s often not what we want though. Two solutions exist. The first one is using the DisplayMemberPath property of the ItemsControl class. This property allows us to specify which property of the bound item should be used for display (for example FirstName). The second solution is using a DataTemplate, a piece of XAML that’s generated for each item in the List. We looked at DataTemplates in part 3 of this series.
  • Binding elements to other elements
    Most of the time, you’ll be binding properties of controls to properties of data objects. Silverlight also supports bindings between two controls. The best example to understand this is probably binding the Value property of a Slider to the Text property of the TextBlock.
  • Implementing INotifyPropertyChanged
    Something we haven’t talked about yet in the data binding engine is the automatic synchronization between source and target control. The data binding engine makes it possible to update the control in the UI when the source value changes. This is only supported if the source class implements the INotifyPropertyChanged interface however. Basically what happens is that when we bind to an object that implements this interface, Silverlight will listen for an event – the PropertyChanged event – being raised from the object. When this event is raised, Silverlight will update the UI accordingly. Note that this only works if the binding is a OneWay or a TwoWay binding!
  • Implementing ObservableCollection
    Similar to the INotifyPropertyChanged but then for collections is the INotifyCollectionChanged interface. This can be used to notify the UI about changes in a collection (items being added or removed). This interface is more complicated however and therefore, a special collection type implementing this interface exists, namely the ObservableCollection. When we use this collection, we’ll see the UI stay in sync with the collection if items are added or removed from the collection.
    • ObservableCollection on MSDN: http://msdn.microsoft.com/en-us/library/ms668604(v=vs.95).aspx
    • http://weblogs.asp.net/joelvarty/archive/2008/11/17/silverlight-databinding-the-observable-collection.aspx
  • Setting binding modes
    Binding modes allow us to specify in what direction the data flows. By default the data flows from the source object to the target control. There are however two options: OneWay and OneTime. OneWay allows updating the UI when the source changes (only works if the source implements INotifyPropertyChanged however). OneTime can be used if you don’t need the synchronization.
    A third mode, TwoWay, allows data to flow in 2 directions: source to target and target to source. This way, we can use data binding also to capture user-entered values.
    • http://msdn.microsoft.com/en-us/library/cc278072(v=vs.95).aspx#direction_of_the_data_flow
    • http://tonesdotnetblog.wordpress.com/2010/03/06/what-are-the-binding-modes-in-silverlight/
    • http://johnpapa.net/all/sivlerlight-2-binding-modes-diagram/
  • Setting a fallback value
    If the data binding expression fails, your application won’t explode! On the contrary, you probably won’t even get any feedback in the UI about it failing. One mechanism to make things easier here is using a fallback value. This value is displayed when the binding fails for any reason.
    • http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.fallbackvalue(v=vs.95).aspx
    • http://www.snowball.be/Silverlight+Advent+Calendar+December+4th+Replacing+Converters+With+New+Data+Binding+Features.aspx
Format data

By default, a data binding sets the value of a property from an object as the value for control property, such as a DateTime value for a TextBlock. We however have options to hook into this process. One solution is using a Converter (see further), an easier solution is using a formatting expression on the binding.

  • Formatting string values in data binding
    By using the StringFormat property of a data binding expression, we can specify how the value for a binding should be formatted. Several formatting strings exist, including currency and date formatting.
  • Formatting culture-specific string values
    • http://timheuer.com/blog/archive/2010/08/11/stringformat-and-currentculture-in-silverlight.aspx
Value Converters

Converters are a great way to do anything with a value before it’s used in the data binding itself. Instead of just using the value in its original format, we can apply a conversion on it. It’s a hook in the data binding process, but it goes further than the StringFormat can go. The latter can just apply conversions on a string, while a converter can apply any transformation.

A converter is nothing more than a class that implements the IValueConverter interface. This interface defines two methods: Convert and ConvertBack. When using a converter on a data binding, the Convert method is automatically invoked when the data flows from the source to the target. Similarly, the ConvertBack is called when data is sent from the target to the source (so when the user can enter data). In the Convert, we can for example add a currency sign to an amount to have it properly displayed. In the ConvertBack, we can remove that currency sign again to be able to save the amount back to a property on the source.

An important feature is that there can be a difference in types between the “input” and “output” of a converter. For example, we can bind an amount (of type int) to a Background property if we apply a converter that checks if the value is greater than zero and returns a green Brush if true and a red one if false.

Learn more about converters using the following links:

Implement data validation

When using TwoWay bindings, we are basically opening up the application for users to enter data. Of course, not all users “behave” like we’d like them to: users will make errors when entering data that could cause problems in our data model. Values that are larger than a specific maximum, a string where an integer is expected… they are all common things we get to deal with in our applications.

To counter this, we obviously have to fall back on the concept of validation. Before the entered data goes back to the source object, we can have Silverlight run validation code that checks if the value is according to one or more validation rules.

In Silverlight 2, the available options for data binding weren’t that rich. With every release, some new options have been added. The most important one however was added with the release of version 4, where 2 new interfaces were added: IDataErrorInfo and INotifyDataErrorInfo. The first one you may know for regular .NET, the second one enables asynchronous validation in Silverlight. This is something we’ll often need: not all validation can be done purely on the client but has to call back to the server-side. A good example is checking the uniqueness of a chosen username: this is typically a check that has to be ran on the database (therefore on the server-side). Since this needs to be done using a service call that runs asynchronously, the INotifyDataErrorInfo comes in handy when we have to wait for a validation result coming back from a service call.

To learn more about data validation, take a look at the following links:

Summary

In this part, we focused on the very important aspect of working with data and learning the data binding mechanism. We also looked at ways to alter the data binding process using converters and we also saw the many ways we can do validation in Silverlight 4, depending on the needs of our application.

In the next art, we’ll be looking at how we can work together with the host platform, including COM, out-of-browser applications and working with the DOM of the surrounding page.

About Gill

Gill Cleeren is Microsoft Regional Director (www.theregion.com), Silverlight MVP (former ASP.NET MVP), INETA speaker bureau member and Silverlight Insider. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium, DevDays NL, NDC Oslo Norway, SQL Server Saturday Switserland, Spring Conference UK, Silverlight Roadshow in Sweden… He’s also the author of many articles in various developer magazines and for SilverlightShow.net. He organizes the yearly Community Day event in Belgium.

He also leads Visug (www.visug.be), the largest .NET user group in Belgium. Gill recently published his first book: “Silverlight 4 Data and Services Cookbook” (Packt Publishing). You can find his blog at www.snowball.be.

Twitter: @gillcleeren


Subscribe

Comments

No comments

Add Comment

Login to comment:
  *      *       

From this series