{"id":1226,"date":"2012-10-10T15:01:14","date_gmt":"2012-10-10T05:01:14","guid":{"rendered":"http:\/\/www.malcolmgroves.com\/blog\/?p=1226"},"modified":"2014-06-10T21:59:12","modified_gmt":"2014-06-10T11:59:12","slug":"livebindings-in-xe3-formatting-your-fields","status":"publish","type":"post","link":"http:\/\/www.malcolmgroves.com\/blog\/?p=1226","title":{"rendered":"LiveBindings in XE3: Formatting your Fields"},"content":{"rendered":"<p>I want to dig a little into the formatting support in LiveBindings. How can we control how our data is displayed when we bind it to UI elements?<\/p>\n<p>If we go back to the traditional data binding support in VCL, different TField descendants exposed different formatting properties. For example,\u00a0<a href=\"http:\/\/docwiki.embarcadero.com\/Libraries\/en\/Data.DB.TNumericField.DisplayFormat\" target=\"_blank\">TNumericField exposes a DisplayFormat property<\/a>\u00a0where you can specify a format string to be used when displaying the contents. TField also exposes an OnGetText event where you can do whatever you like to the value before it is displayed in the UI.<!--more--><\/p>\n<div id=\"attachment_1236\" style=\"width: 333px\" class=\"wp-caption alignnone\"><a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LB_Formatting1.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1236\" class=\"wp-image-1236 \" title=\"LB_Formatting1\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LB_Formatting1.jpg\" width=\"323\" height=\"120\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LB_Formatting1.jpg 462w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LB_Formatting1-300x111.jpg 300w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LB_Formatting1-297x109.jpg 297w\" sizes=\"auto, (max-width: 323px) 100vw, 323px\" \/><\/a><p id=\"caption-attachment-1236\" class=\"wp-caption-text\">The DisplayFormat property of a TFloatField being used to control the formatting of the text in the linked Edit box.<\/p><\/div>\n<p>The good news is that if you are binding from a TDataset using a TBindSourceDB, all of these will be respected by LiveBindings.<\/p>\n<p>But what if you&#8217;re not binding from a TDataset? Let&#8217;s try it out and see.<\/p>\n<p style=\"text-align: left;\">Create a new FireMonkey Desktop application and drop down a TPrototypeBindSource. Next, define two fields like so:<br \/>\n<a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting1.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter  wp-image-1293\" title=\"LBFormatting1\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting1.jpg\" width=\"238\" height=\"205\" \/><\/a><br \/>\nThen, bind those fields to some controls as shown below:<\/p>\n<p style=\"text-align: left;\"><a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting2.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter  wp-image-1292\" title=\"LBFormatting2\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting2.jpg\" width=\"343\" height=\"151\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting2.jpg 429w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting2-300x132.jpg 300w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting2-297x130.jpg 297w\" sizes=\"auto, (max-width: 343px) 100vw, 343px\" \/><\/a><br \/>\nNote, you can do this either by dropping the components onto the form and wiring them together using the LiveBindings Designer, or right click on the fields in the TPrototypeBindSource in the LiveBindings\u00a0\u00a0Designer\u00a0and select Link to New Control.<\/p>\n<p style=\"text-align: left;\">Still in the LiveBindings designer, select the arrow that runs between the Lastname field in the PrototypeBindSource and the Edit box. This will select the aptly named TLinkControltoField instance that LiveBindings is using to bind the Edit Control to the Lastname field. It has a CustomFormat property, where we can enter an expression that will be used to format our display. Within this expression, %s represents the underlying field value, and importantly, we can call methods within the expression we enter. In this example I&#8217;ve entered &#8220;Mr &#8221; + UpperCase(%s) as the value, and given I used ColorNames as the generator for this field, I end up with what looks like a draft list of characters from <a href=\"http:\/\/www.imdb.com\/title\/tt0105236\/\" target=\"_blank\">Reservoir Dogs<\/a>.<\/p>\n<div id=\"attachment_1298\" style=\"width: 488px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting7.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1298\" class=\" wp-image-1298\" title=\"LBFormatting7\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting7.jpg\" width=\"478\" height=\"304\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting7.jpg 598w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting7-300x190.jpg 300w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting7-297x188.jpg 297w\" sizes=\"auto, (max-width: 478px) 100vw, 478px\" \/><\/a><p id=\"caption-attachment-1298\" class=\"wp-caption-text\">The CustomFormat expression we&#8217;re using to format the Lastname column in the Grid.<\/p><\/div>\n<p>An important question is where are these methods coming from? Select the BindingsList that was added to your form when you started wiring up controls and notice it has a Methods property. In here we can see all the methods currently available to your expressions. Be aware though, that these method names are case sensitive.<\/p>\n<div id=\"attachment_1290\" style=\"width: 417px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting4.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1290\" class=\" wp-image-1290 \" title=\"LBFormatting4\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting4.jpg\" width=\"407\" height=\"450\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting4.jpg 509w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting4-271x300.jpg 271w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting4-297x327.jpg 297w\" sizes=\"auto, (max-width: 407px) 100vw, 407px\" \/><\/a><p id=\"caption-attachment-1290\" class=\"wp-caption-text\">The methods available to our binding and format expressions, including my custom CurrencyToStr and StrToCurrency methods.<\/p><\/div>\n<p>These standard methods are a good start, but what if we want to do something in our expression that is not already covered by one of the standard methods? Well, write a custom one of course!<\/p>\n<p>In the <a href=\"https:\/\/github.com\/malcolmgroves\/delphi-samples\/tree\/master\/LiveBindings\/Formatting%20your%20Fields\" target=\"_blank\">sample code for this article<\/a> you&#8217;ll find a package called MGCustomLiveBindingMethods, and within it a unit called CurrencyToStrMethod. In it we&#8217;re registering two custom methods,\u00a0CurrencyToStr and StrToCurrency (actually, you can see them in the list of methods above). CurrencyToStr simply takes a Currency and returns a string, formatted with the appropriate currency prefix according to the Locale settings of the underlying operating system, while StrToCurrency does the reverse, stripping all currency formatting out of the string.<\/p>\n<pre lang=\"delphi\">unit CurrencyToStrMethod;\r\n\r\ninterface\r\n\r\nimplementation\r\nuses System.Bindings.Methods, System.SysUtils, MethodUtils;\r\n\r\nconst\r\n  sIDCurrencyToStr = 'CurrencyToStr';\r\n  sIDStrToCurrency = 'StrToCurrency';\r\n\r\nprocedure RegisterMethods;\r\nbegin\r\n  TMethodUtils.RegisterMethod&lt;Currency, string&gt;(sIDCurrencyToStr,\r\n    function(AValue: Currency): string\r\n    begin\r\n      Result := CurrToStrF(AValue, ffCurrency, 2);\r\n    end);\r\n\r\n  TMethodUtils.RegisterMethod&lt;string, Currency&gt;(sIDStrToCurrency,\r\n    function(AValue: string): Currency\r\n    var\r\n      C: char;\r\n      LDigits: string;\r\n    begin\r\n      for C in AValue do\r\n        case C of\r\n          '0'..'9',\r\n          '.': LDigits := LDigits + C;\r\n        end;\r\n          Result := StrToCurr(LDigits)\r\n    end);\r\nend;\r\n\r\nprocedure UnregisterMethods;\r\nbegin\r\n  TBindingMethodsFactory.UnRegisterMethod(sIDCurrencyToStr);\r\n  TBindingMethodsFactory.UnRegisterMethod(sIDStrToCurrency);\r\nend;\r\n\r\ninitialization\r\n  RegisterMethods;\r\nfinalization\r\n  UnregisterMethods;\r\nend.<\/pre>\n<p>In the Initialization section we&#8217;re calling RegisterMethods, which in turn is calling TMethodUtils.RegisterMethod, once for each custom\u00a0method\u00a0we want to register. This is a generic method where we can specify the types of parameters expected and returned by our custom method. In the first case, the generic types we&#8217;re specifying are Currency and string for the parameter and return types respectively. Given this is for our CurrencyToStr method, that makes sense. The second method we&#8217;re registering has these types reversed, which again should make sense given it is for the StrToCurrency method.<\/p>\n<p>The actual\u00a0parameters\u00a0to the RegisterMethod call are a string, which is the method name, and an anonymous method which is the actual implementation of our method.<\/p>\n<p>I need to point out that this is not the way you&#8217;ll see the default methods registered, and in fact was not the way I was registering my custom methods in the first draft of this article. Prior to TMethodUtils, there was quite a lot of scaffolding code you needed to write to register your methods, but thankfully <a href=\"http:\/\/blogs.embarcadero.com\/jimtierney\/\" target=\"_blank\">Jim Tierney<\/a> came to the rescue and provided this unit which dramatically simplifies the process.<\/p>\n<div class=\"alert alert-warning\">NB: MethodUtils will at some point roll back into the core product, at which point I&#8217;ll need to remove it from\u00a0my\u00a0package. If you expect to use this unit in multiple packages, you should either rename it or put it in its own, standalone package.<\/div>\n<p>Lastly, and importantly, the finalization section reverses the registration of our methods.<\/p>\n<div style=\"width: 264px\" class=\"wp-caption alignright\"><a style=\"text-decoration: underline; outline: #000000;\" href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting5.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-1289 \" title=\"LBFormatting5\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting5.jpg\" width=\"254\" height=\"270\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting5.jpg 317w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting5-282x300.jpg 282w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting5-297x315.jpg 297w\" sizes=\"auto, (max-width: 254px) 100vw, 254px\" \/><\/a><p class=\"wp-caption-text\">The CustomFormat and CustomParse properties of our binding, using our custom methods.<\/p><\/div>\n<p>Once this is done, compile the package, then right-click on it in the Project Manager and Install it. Now, back in my project, I can select the binding that connects my Amount field to the TEdit and set its CustomFormat property to CurrencyToStr(%s) to format the Amount appropriately.That&#8217;s great for formatting the amount, ie. going from the field to the control, but what happens when we need to go the other way, from the control back to the field, ie. when someone edits the value and we have to strip out the formatting? Well, that&#8217;s what the CustomParse property is for, sitting right underneath the CustomFormat property we just used. In here we&#8217;ll use StrToCurrency(%s) to undo the formatting.<\/p>\n<p>If you now run up the application, you can see that the Edit box displays the formatted amount correctly. We can edit the value, and the unformatted result is what should end up back in our field (as can be seen by the Label we have bound to the same field).<\/p>\n<div id=\"attachment_1288\" style=\"width: 260px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting6.jpg\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1288\" class=\" wp-image-1288 \" title=\"LBFormatting6\" alt=\"\" src=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting6.jpg\" width=\"250\" height=\"326\" srcset=\"http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting6.jpg 312w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting6-229x300.jpg 229w, http:\/\/www.malcolmgroves.com\/blog\/wp-content\/uploads\/2012\/10\/LBFormatting6-297x388.jpg 297w\" sizes=\"auto, (max-width: 250px) 100vw, 250px\" \/><\/a><p id=\"caption-attachment-1288\" class=\"wp-caption-text\">Our form at runtime. Note we have targeted the formatting only at the specific control we want, in this case, the Amount Edit.<\/p><\/div>\n<p>It&#8217;s hopefully apparent by now that the CustomFormat and CustomParse expressions we&#8217;re entering are specific to that binding. As above, the grid and the label don&#8217;t show the formatting as we have not set the properties on those links. This is another good reason I think to build up a library of your commonly used custom expression methods, so you can very quickly apply them to your links without having to debug complex expressions every time.<\/p>\n<p style=\"text-align: left;\">That&#8217;s enough for this post, but next up, a related topic on writing custom generators for TPrototypeBindSource, and then I want to tackle a bigger topic related to LiveBindings: <a href=\"http:\/\/en.wikipedia.org\/wiki\/MVVM\" target=\"_blank\">Model-View-ViewModel (MVVM)<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I want to dig a little into the formatting support in LiveBindings. How can we control how our data is displayed when we bind it to UI elements? If we go back to the traditional data binding support in VCL, different TField descendants exposed different formatting properties. For example,\u00a0TNumericField exposes a DisplayFormat property\u00a0where you can [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[116],"tags":[64,19,48,89],"class_list":["post-1226","post","type-post","status-publish","format-standard","hentry","category-livebindings","tag-cbuilder","tag-delphi","tag-embarcadero","tag-livebindings"],"_links":{"self":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1226","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1226"}],"version-history":[{"count":51,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1226\/revisions"}],"predecessor-version":[{"id":1543,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1226\/revisions\/1543"}],"wp:attachment":[{"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1226"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1226"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.malcolmgroves.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1226"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}