<a href="http://www.omniture.com" mce_href="http://www.omniture.com" title='Web Analytics'><img alt='' border='0' height='1' src="http://mssto.112.2o7.net/b/ss/msstoextblogsnojs/1/H.20.2--NS/0" mce_src="http://mssto.112.2o7.net/b/ss/msstoextblogsnojs/1/H.20.2--NS/0" width='1' /></a>","bodyAsHTML":"Hello Windows 8 XAML developer. XAML is a declarative UI language; \r\nits most powerful feature is surely data binding.  But, I admit, with \r\nsuch power comes a lot of things to know. Let’s take a minute to step \r\nback, smell the roses, and build out some simple bindings.

Ready to learn?

Referencing a control

Referencing\r\n a control in XAML is referencing a class. Declare it in XAML and the \r\nclass’ constructor is executed. Your control is now in the logical tree.\r\n Every control is part of a hierarchy, with the top-most control being \r\nthe page element.

\"image\"

Adding content to a control

Not\r\n all XAML controls are content controls, but most are. Control controls \r\nallow you to put almost anything in them. That means you can put text in\r\n the content property, like this:

\"image\"

The\r\n area between the button XAML tags defaults to its content property. So,\r\n you can put simple (like above) or complex (like below) content \r\ndirectly between the tags:

\"image\"

In\r\n the code above, I place a grid inside my button and even another \r\nbutton. This is all possible because “content” in XAML allows for almost\r\n anything.

Setting a property

Not all properties are \r\ncontent properties. Like XML or HTML you can set property values simply \r\nby setting the attribute of the control, like this:

\"image\"

In\r\n the code above, the content property interprets the string as a string.\r\n But some properties require integers, doubles, colors, and more. XAML \r\nautomatically converts to these types for you.

Setting a complex property

Complex\r\n property values can’t be jammed into an attribute string. When you have\r\n a complex value to set to a property, you do it like this:

\"image\"

Binding a property

\"image\"

Hard\r\n coding a property value may not be an option. For this reason, XAML \r\nsupports binding. Say you have a class (above) that you set to the \r\ndatacontext property of a control. Once set, that control and all of its\r\n children can bind to it – since properties propagate down through the \r\nhierarchy tree.

The three binding syntaxes (below) function identically:

\"image\"

In\r\n the code above, the first (one) syntax explicitly calls the path \r\nbinding property. This, however, is the default property so the second \r\n(two) syntax omits it. The third (three) syntax uses the expanded \r\nproperty syntax and sets the value with the fully qualified binding \r\nobject. The three are identical in function and performance – only the \r\nsyntax is different.

Binding with a converter

Sometimes \r\nthe value you want to bind isn’t the value you want to show. In the \r\nexample above, I want to show the ButtonText value in all upper case. \r\nSince this is simply a UI requirement, we don’t want to change class, we\r\n just want to convert the value being displayed.

\"image\"

The\r\n code above shows the implementation of a simple value converter for \r\nXAML binding. This converter takes the value and changes it to upper \r\ncase. Since you write the converter, it means you can make it do \r\nwhatever you want. Here’s how you use them:

\"image\"

There\r\n are two parts to the code above. The first the resource. When I want to\r\n use a converter in my XAML, I need to reference my value converter \r\nclass in the resources of any control higher in the control hierarchy, \r\neven the page. Then, I can references throughout my XAML.

The \r\nsecond part of the code shows the simple binding syntax we saw before. \r\nHowever, it adds the extra ‘Converter’ portion after the comma. This \r\nreferences the resource we added above the control by name. The syntax \r\ntells XAML to run the value through the converter before displaying it.

Using converter parameters

Converters\r\n can also be passed parameters from the bound control. This gives you \r\neven more control over the logic inside the converter. It is optional, \r\nbut it is also a powerful option.The following syntaxes use a parameter –\r\n like above, these different techniques function identically:

\"image\"

Binding to an element

Sometimes\r\n the value of one control’s property needs to match the value of another\r\n control’s property. XAML allows this by referencing another control by \r\nname. The binding syntax continues to be the same, but allows you to \r\nenrich it more detail, like this:

\"image\"

 

In\r\n the code above, this binding syntax sets the button’s content to the \r\ntextbox’s text value. The complex interaction between controls is \r\naccomplished without any code behind. If you were to write the \r\nequivalent code behind it would look like this:

\"image\"

Note: as the user changes the textbox, the content of the button is updated.

Binding modes

If\r\n you bind the property of any input control (a slider, a textbox, a \r\nradiobutton, et al) – basically anything the user interacts with – then \r\nthe syntax would look something like this:

\"image\"

But\r\n this is a problem. This syntax only reads the value; it doesn’t write \r\nthe value back. Input controls typically want to write the value back. \r\nFor this scenario, XAML provides binding modes: OneTime (most \r\nefficient), OneWay (default), and TwoWay (for input controls).

\"image\"

Inline invocation

As\r\n I mentioned above, whenever you declare a control in XAML you are \r\ninstantiating a class. And, just like using a converter resource \r\ninstantiates the converter class, you can instantiate any class you want\r\n to – this is very helpful with binding. Consider a class like this:

\"image\"

In\r\n the code above, the class has a constructor where its property value is\r\n set. But how do you use this in your XAML? Just like we made the \r\nconverter a resource, we make our class a resources, like this:

\"image\"

Now\r\n we can reference this as a source for our binding. Source is slightly \r\ndifferent. It is basically telling the XAML engine to ignore the \r\ndatacontext of the control and look elsewhere instead. In this case, we \r\nwill tell it to look at this MyRecord resource we just created, like \r\nthis:

\"image\"

The datacontext

Referencing\r\n a source over and over is a lot of useless and redundant code. Instead,\r\n we want to set the datacontext of a control. The datacontext is the \r\ndefault source of a binding. What’s nice is that we can set a control’s \r\ndatacontext or its parent or its parent’s parent, and so on.

We can set it in code like this:

\"image\"

We can also set it in XAML like this:

\"image\"

Notice\r\n in the XAML above that we do not give a name to our MyRecord reference.\r\n This is because we will not be referencing it. Simply because we have \r\nset it as datacontext, it will flow down through the hierarchy. And, if \r\nit is not interrupted, our button can use it like this:

\"image\"

Look\r\n familiar? This is the very first binding syntax we looked at up top. \r\nOnce you set the datacontext you can set bind to it from any child \r\nelement.

Deep binding

Our example is simple, but \r\nsometimes you want to bind to more than just the properties of a class. \r\nIf a property is a complex type (a class) you might want to bind to the \r\nproperties of that class. Is this kind “deep binding” possible? You bet.\r\n Look:

\"image\"

In\r\n the code above, we recognize that a string is actually a class. And the\r\n string class has a property of length. So, we bind to it with syntax \r\nvery similar to how we access properties in C#. Let’s pretend now that \r\nwe bind to an array of strings, how would we access an item and its \r\nproperties?

\"image\"

In\r\n the code above, I treat ButtonText like a string array (string[]) and \r\naccess the first item (zero-based) and then a property of that first \r\nitem. This is quite a complex operation if you think about it. But the \r\nXAML syntax keeps it simple, consistent, and compact.

But wait, there’s more

Believe\r\n it or not, there’s even more to XAML binding. But, in the sections \r\nabove I walk through what has to be the most common and surely the most \r\nimportant parts. The syntax is simple, but looks pretty tricky when you \r\nare new. I tell you what: create a simple project and start binding to \r\nyour own custom class. With a little practice you’ll start to feel more \r\ncomfortable binding everything!

Here are some resources (not all Windows 8, I know)

  1. Designing for the Modern UI
  2. App Development for Modern Devices (Networking)
  3. Basics of XAML: Canvas and Rectangle
  4. Windows Phone 7 Jump Start Video Series
  5. Deep Expression Blend (XAML)
  6. XAML (SL) 101
  7. XAML (WPF) 101
  8. Build a Windows 8 App in 30 Days
  9. Early Access to Windows 8 SDK
  10. Visual Studio Express 2012 Free Trial
  11. Tutorial: WinPhone to Windows 8
  12. Windows Phone SDK 7.1 Free Download

Best of luck!

 

 

 

\r\n\r\n","author":{"id":954995,"username":"Jerry Nixon","realname":null,"emailHash":"1679f0ca80c657f1fca8fbcc74eeefe1","avatar":"https://secure.gravatar.com/avatar/1679f0ca80c657f1fca8fbcc74eeefe1?d=identicon&r=PG","reputation":0},"activeRevisionId":543465,"revisionIds":[543465],"lastActiveUserId":954995,"lastActiveDate":1350435018000,"parentId":null,"parentAuthor":null,"originalParentId":null,"childrenIds":[],"commentIds":[],"marked":true,"topics":["mobile","tutorial",".net & windows","windows 8","xaml"],"primaryContainerId":8,"containerIds":[7,8],"plug":"xaml-binding-basics-101","wiki":false,"score":0,"depth":0},"enableThreadedComments":true,"portal":{"topic":{"id":"29","type":"topic","creationDate":1434655010000,"creationDateFormatted":"06/18/2015 07:16 PM","name":"mobile","createdBy":{"id":2,"username":"matt"},"parentTopics":[],"childTopics":[],"usedCount":36135},"blurb":"Mobile App developer news, tools and training resources from DZone, the trusted source for advanced software design, web development and devops best practices.","code":"mobile","id":9,"creationDate":1434673929000,"creationDateFormatted":"06/19/2015 12:32 AM","displayTitle":"Mobile Zone: Mobile app development news, tutorials & tools","title":"Mobile","new":false,"order":9,"shortTitle":"mobile-app-developer-tutorials-tools-news","color":"yellow","pageTitle":"Mobile App Development News, Tools & Training - DZone","active":true,"modificationDate":1437510259000,"modificationDateFormatted":"07/21/2015 08:24 PM"},"contentType":"article"}],"loadedStyles":[["/lib/bootstrap/bootstrap.less","/lib/font-awesome/font-awesome.less","/lib/fontello/css/fontello.css","/lib/fontello/css/animation.css","/lib/angular-ui/select.css","/lib/ngDialog/css/ngDialog.css","/less/ngDialog-theme.less","/lib/bootstrap-switch/bootstrap-switch.css","/less/dzone20.less","/less/fonts.less","/less/directives.less","/lib/slick/slick.css","/lib/bootstrap-slider/bootstrap-slider.css","/less/layout.less","/widgets/article/content/article-content.less","/widgets/article/infoBar/widget.less","/widgets/components/slider/widget.less","/widgets/content/commentsSlider/widget.less","/widgets/header/blackBar/widget.less","/widgets/header/main/header-common.less","/widgets/header/main/widget.less","/widgets/sidebar/content/list/list.less","/widgets/sidebar/tapBar/sidebar-list.less","/widgets/sidebar/tapBar/widget.less","/widgets/users/UserHomeMiniProfile/widget.less"]],"loadedScripts":[["/lib/jquery/jquery.js","/lib/lodash/lodash.js","/lib/moment/moment.js","/scripts/utils.js","/lib/angular/angular.js","/lib/angular/angular-sanitize.js","/lib/local-storage/angular-local-storage.js","/lib/bootstrap/bootstrap.js","/lib/angular-ui/bootstrap.js","/lib/angular-ui/select.js","/lib/bootstrap-switch/bootstrap-switch.js","/lib/ngDialog/js/ngDialog.js","/lib/angular-moment/angular-moment.js","/scripts/app.js","/scripts/socket.js","/scripts/services.js","/scripts/ui-services.js","/scripts/directives.js","/scripts/filters.js","/lib/angular-touch/angular-touch.min.js","/lib/elastic/elastic.js","/lib/ng-file-upload/angular-file-upload-all.js","/lib/angular-deckgrid/angular-deckgrid.js","/scripts/dzone.js","/scripts/ads.js","/scripts/head.js","/scripts/links.js","/scripts/utilities/directives.js","/scripts/utilities/services.js","/scripts/utilities/image-editor.js","/lib/bootstrap-slider/bootstrap-slider.js","/lib/bootstrap-slider/directive.js","/lib/angular-draganddrop/draganddrop.js","/widgets/article/content/utils.js","/widgets/article/infoBar/services.js","/widgets/components/slider/service.js","/widgets/header/main/angulartics-ga.js","/widgets/header/main/angulartics.js","/widgets/header/main/resize.js","/widgets/sidebar/content/list/service.js","/widgets/sidebar/tapBar/directive.js","/widgets/sidebar/tapBar/service.js"]],"TH_CSRF":"2606065585800799302","botInfo":[{"isRenderBot":false}],"request":[{"site":{"id":7,"title":"DZone: Programming & DevOps news, tutorials & tools","keywords":"programming, software development, devops, java, agile, web, iot, database, mobile, big data, cloud","description":"Programming, Web Development, and DevOps news, tutorials and tools for beginners to experts. Hundreds of free publications, over 1M members, totally free.","name":"DZone.com"},"dev":false,"cdn":["dz2cdn1.dzone.com","dz2cdn2.dzone.com","dz2cdn3.dzone.com","dz2cdn4.dzone.com"],"theme":"dz20","context":"","user":{"id":2500002,"authenticated":false,"name":"Anonymous","realName":null,"avatar":"https://secure.gravatar.com/avatar/?d=identicon&r=PG","profile":"/users/2500002/anon-user.html"}}],"portals":[[{"topic":8,"id":2,"shortTitle":"agile-methodology-training-tools-news","color":"red","name":"Agile","code":"agile","url":"/agile-methodology-training-tools-news"},{"topic":6129,"id":3,"shortTitle":"big-data-analytics-tutorials-tools-news","color":"green","name":"Big Data","code":"big-data","url":"/big-data-analytics-tutorials-tools-news"},{"topic":30,"id":4,"shortTitle":"cloud-computing-tutorials-tools-news","color":"orange","name":"Cloud","code":"cloud","url":"/cloud-computing-tutorials-tools-news"},{"topic":59,"id":5,"shortTitle":"database-sql-nosql-tutorials-tools-news","color":"purple","name":"Database","code":"database","url":"/database-sql-nosql-tutorials-tools-news"},{"topic":31,"id":6,"shortTitle":"devops-tutorials-tools-news","color":"yellow","name":"DevOps","code":"devops","url":"/devops-tutorials-tools-news"},{"topic":1138,"id":7,"shortTitle":"enterprise-integration-training-tools-news","color":"green","name":"Integration","code":"integration","url":"/enterprise-integration-training-tools-news"},{"topic":48,"id":8,"shortTitle":"iot-developer-tutorials-tools-news-reviews","color":"orange","name":"IoT","code":"iot","url":"/iot-developer-tutorials-tools-news-reviews"},{"topic":1,"id":1,"shortTitle":"java-jdk-development-tutorials-tools-news","color":"purple","name":"Java","code":"java","url":"/java-jdk-development-tutorials-tools-news"},{"topic":29,"id":9,"shortTitle":"mobile-app-developer-tutorials-tools-news","color":"yellow","name":"Mobile","code":"mobile","url":"/mobile-app-developer-tutorials-tools-news"},{"topic":653,"id":10,"shortTitle":"apm-tools-performance-monitoring-optimization","color":"red","name":"Performance","code":"performance","url":"/apm-tools-performance-monitoring-optimization"},{"topic":35,"id":11,"shortTitle":"web-development-programming-tutorials-tools-news","color":"orange","name":"Web Dev","code":"webdev","url":"/web-development-programming-tutorials-tools-news"}]],"matchedUrl":{"name":"dzone:articles:view","mapping":"/articles/**","mappingPatterns":{}},"requiresModule":["angulartics","angulartics.google.analytics","dndLists","generalDirectives","monospaced.elastic","angularFileUpload","akoenig.deckgrid","ui.bootstrap-slider","ngSanitize","ui.select","ui.bootstrap","angularMoment","ngTouch","ngDialog","LocalStorageModule"]}; } catch(e) { console.error(e); }
4
Notification
  • Adam Van Grack started following you

  • Jessica Conaghan, Gumption Scott and 6 commented on a link you posted

    T-Mobile Unvells Cheaper, More Basic 'Simple Prepaid' Phone Plans

  • Jessica Conaghan replied on a comment you posted

    CSS counters are one of those "oh neat, didn't know CSS could do that" features with a lot of Xubuntu 14.10 Utopic Unicorn is the latest release of xubuntu based on Ubuntu 14.10

  • Jessica Conaghan started following you

See All
POWERED BY DZone TeamHub
","source":"http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html","views":5491,"articleDate":1350435018000,"tldr":null,"originalSource":"http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html","published":true,"nComments":0,"articleType":""}]; WMODEL_DATA.perms = {"canDecidePick":false,"canPublish":false}; WMODEL_DATA.isPreview = false; WMODEL_DATA.OPTIONS = {}; TH.installWidgetController('article.content', 'articleContent7', WMODEL_DATA, typeof controller == 'function' ? controller : null, [{name: 'partners', data: true},{name: 'DEFAULT', data: true}], ' oUhbblYOaqbcblYOaqbcC', null); })(); (function() { function controller($scope, $service, $location, SideBarService, TH$Request) { SideBarService.ctx.pageSize = $scope.pageSize; SideBarService.ctx.isPreview = $scope.isPreview; SideBarService.ctx.mode = $scope.mode; SideBarService.fn.loader = $service; SideBarService.fn.scrollCheck = function() { $scope.$emit('thIfScrollCheck'); }; var currentFilter; $scope.$on('$locationChangeSuccess', function() { if (!$location.search().filter) { $scope.filter = 'latest'; } else { $scope.filter = $location.search().filter; if ($scope.filter == 'latest') { $location.search('filter', null); } } if (currentFilter == $scope.filter) { return; } currentFilter = $scope.filter; SideBarService.ctx.filter = $scope.filter; }); $scope.display = SideBarService.getList(); $scope.$watchCollection(function() { return SideBarService.getList(); }, function (n) { $scope.display = n; }); $scope.isActive = SideBarService.isActive; $scope.isExcluded = SideBarService.isExcluded; $scope.loadMore = SideBarService.load; $scope.loading = function() { return SideBarService.ctx.loading; } } var WMODEL_DATA = {}; WMODEL_DATA.pageSize = 20; WMODEL_DATA.isPreview = false; WMODEL_DATA.OPTIONS = {}; WMODEL_DATA.mode = null; TH.installWidgetController('sidebar.content.list', 'sidebarContentList10', WMODEL_DATA, typeof controller == 'function' ? controller : null, [{name: 'DEFAULT', data: true}], ' oUhbkSMaaqbcdvVkcC', null); })(); (function() { var WMODEL_DATA = {}; WMODEL_DATA.OPTIONS = {}; TH.installWidgetController('sidebar.tapBar', 'sidebar', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhbkSMadabfWVcC oUhbkSMadabbWQbVkcC', null); })(); (function() { function controller($scope, shareThis, TH$Dialog, TH$Service) { $scope.getEditUrl = function(id, type) { if (!type || type == 'article') { return '/content/' + id + '/edit.html'; } else { return '/dzone/staff/' + type + (type == 'refcard' ? 'z' : 's') + '/' + id + '/edit.html'; } } $scope.share = function(socialNet, url, title){ shareThis.shareThis(socialNet, url, title); }; $scope.canDelete = function(article) { return article.canDelete; } $scope.edit = function(link) { TH$Dialog.open({ loadWidget: 'links.postPreview', widgetArgs: { edit: link.id }, size: 'xbig' }).then(function (result) { $scope.link.title = result.title; $scope.link.linkDescription = result.content; $scope.link.thumb = result.thumb; $scope.link.tags = result.topics; }); }; $scope.deleteLink = function(article) { var title = article.title; var type = 'link'; if(article.header){ title = (article.header.type == 'article') ? article.header.title : article.title; type = (article.header.type == 'article') ? 'article' : 'link'; } TH$Dialog.confirm('Do you want to delete "' + title + '"?').then(function() { return TH$Service.action('delete', {type: type, id: article.id}); }).then(function() { article.deleted = true; }); }; } var WMODEL_DATA = {}; WMODEL_DATA.OPTIONS = {}; TH.installWidgetController('content.commentsSlider', 'contentCommentsSlider9', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhbaqbcaibvnWffWVcC', null); })(); (function() { var WMODEL_DATA = {}; WMODEL_DATA.name = "commentsSlider"; WMODEL_DATA.slot = null; WMODEL_DATA.OPTIONS = {"name":"commentsSlider"}; TH.installWidgetController('components.slider', 'componentsSlider8', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhballbvbdSaoUhM', null); })();