This is the third post in a series about creating a Universal App for Windows. I’m going to write about one of the most powerful concepts ever created by the mankind - Data Binding.
Data Binding and Data Contexts
I spent several nights to fully grasp the idea of DataContexts and DataBinding in XAML. And now I’m willing to share some resources that helped me greatly in this quest.
An outstanding video by Bob Tabor about Data Binding, Data Sources and Data Contexts. This is the must-see. If you want to start with something, this video is probably the best to get to know data binding in XAML.
Pluralsight course on DataBinding by Thomas Claudius Huber. It helped me a lot, especially to understand what is actually can be “data bound”.
How to databind a pivot control - helped me understand how using DataContext I could easily bind my data to my controls in design time. A very informative post, definitely worth checking out.
Context is the Thing
So to summarize what I have learned, with DataContext property it is possible to reach the deepest level of your control hierarchy while still using only declarative syntax of XAML.
In my app I was able to specify a DataContext once for my Pivot control and then bind to data from that DataContext. Look:
In the code-behind file, I have a property QuoteListViewModel and I put it in the context the top-most level - the Page itself. After I’ve done that, each control on my page gains access to this data context and I’m able to bind properties of my context.
This can be seen in code. Pivot is taking us even further - it sets its context to QuoteListViewModel.Quotes which is actually a ViewModel for this control.
One other thing I discovered when debugging this stuff is that it’s extremely hard to debug declarative data bindings. However, there is one way that actually works - you need to closely watch the Output window when your app is running. All binding errors will be logged there:
There was a lot of refactoring besides the Data Binding in this part of the series.
- Flyout menu works properly and looks native (thanks to Tim Gabrhel’s post Flyouts on Windows Phone).
- Refactored QuoteListPage.xaml.cs, now it has become much more responsive.
- Distanse calculations using MapLocationFinder class, now each item has a corresponding distance from your current location.
A full source can be found on Github as usual under week3 tag.