Monday, April 22, 2019 ..:: Home ::.. Register  Login
All blog entries are the opinions of the author and do not necessarily reflect the opinions of their employer. All the code presented is for explanation and demonstration purposes only. Any damages incurred to your site and/or data are not the responsibility of the author. Every effort is taken to ensure the code properly compiles, however sometimes there are some hiccups and you might be required to do your own debugging.
   TechTidBits (Blog)  

Simple XAML Converter and Even Simpler Data Binding to Control

Nov 29

Written by:
Friday, November 29, 2013 4:43 PM  RssIcon

imageAre you starting out with XAML?  Trying to figure out Converters?  What about data binding to another element?  Here’s a simple example to follow.

If you’re getting used to XAML, I’m sure you’ve heard of Converters and Data Binding?  Well, in following some MS Virtual Academy videos, I saw some cool golden nuggets I want to try out and in doing so, want to share them with you.  I’m doing this to help me remember but also to help make some magical graphical links which I HOPE will help you and I to remember these KEY xaml concepts when we’re coding!

The example below, simply takes the value from a slider control and translates the numerical value to a grade value (<50 = F, <80 = B, < 100 = A+ that kind of stuff).  The idea here is two fold, we need to get the value of the slider and then we translate that numerical (int32) value into a string (letter grade) and display it.





Ok, if you’re thinking this is overly simplistic. YUP!  You’re right, if you’re here, you’re trying to learn a bit about the mechanics.  Here we go!

First off, let’s create our converter class.  I would suggest making your class public, makes reusing MUCH simpler later on (default is nothing, which is actually private).  Next extend IValueConverter and if you type out properly (proper case I mean), then VS will let you CTRL+. (or use mouse click) and it’ll let you setup your using statements to Windows.UI.Xaml.Data.


After you do that, you COULD type out the exact signatures of the methods you need to implement IValueConverter, but why bother?  Why not let VS do the heavy lifting FOR YOU?  SURE!  Use your mouse, or CTRL+. again, and pick the first option.


What’s important here is you get the exactly correct method signatures you need to implement!


Now we need to add some code to the converter.  The key to understand here is we’re going to GET a value, an integer in fact, and we need to change….convert it to another data type, to a string, which the TextBox is going to understand.  Yes, the astute readers/coders are going to say “but Peter, a TextBlock/TextBox already understands numbers/ints.  True, but this conversion logic works for any type of incoming and out going data type!  Therefore, this is the same pattern for changing a number to a background Color class, or an ImageSource, etc.  I’m just focusing on the mechanics (maybe later on I’ll do an image one?).

Below is just ONE implementation of the grade to number algorithm (algorithm might be a bit of over selling LOL).  The key here is you’re accepting ANYTHING……ie an object, we’re ASSUMING it’s a number, but we still need to check for it!  That’s the Int32.TryParse method’s job.  Remember one small detail, bad data coming in, doesn’t make your XAML apps fail or break, they just keep on rolling.  We do that here too by just passing back our defaulted value of F (you could do a String.Empty or DNC = Did Not Complete if you wish).  Lastly, we need to pass back the value in the translated data type we want to display.  In our case it’s a String, but don’t forget, String extends Object right?   So we’re not breaking the method signature.


Next we’ll add in our slider to the MainPage.xaml. (Unfortunately since this blog engine doesn’t like the xaml syntax IN the blog, I have to take screen caps, BUT there is the codeplex for real samples).  Nothing complicated, the only things different are the extra attributes for alignment, margins, value for the initial value), the only REAL IMPORTANT thing is the x:Name, but you just need to remember yours.


Next, you need to add in your code to connect a TextBlock to the slider’s changing value.  NO, no no, don’t start F7 and going into codebehind!  We’re doing this all in xaml tonight!  But there’s a few things we need, you COULD

-put in a TextBlock, setup a Text attribute, set the binding and converter

-setup page resource to your newly create GradeConverter

-setup the xml namespace so the C# compiler knows where to FIND your newly created GradeConverter

The problem with doing it this way, although technically NOTHING is wrong, but is that you don’t really know if or WHEN you got things right, until you’re all done!  DOH!  If you’re like me, you probably like to see things working as quickly as possible!  SO, I suggest working backwards!

Ok, so let’s setup our local namespace so that WHEN we goto reference our converter, the compiler WILL find it.  You put this up in the Page tag


Next, right after the opening Page tag, you add the following,


If you were to compile this NOW (F6) you’ll (HOPEFULLY!) get a clean compile.  If not, then THIS is where you need to focus on.  Ok, if you’re here now, next is where we’ll add in our linked in TextBlock.


First off, there’s the TextBlock definition.  Next we give it a (1) Text attribute/property and tell xaml it’s a Binding, you use the parenthesis for that “{“ and “}”. Next (2) we say what element, or other control we want to get something from and in this case it’s the Path to Value (1).  You see it’s the Value attribute/property of the Slider we want to grab.  Next (4) we setup our converter, it gets slightly tricky here, so just copy it out, then come back here.  Ok, you’re back?  Good.  Just like the Binding, we’re setting up a xaml connection to our GradeConverter, but we’re using a StaticResource, which is what we described up above in the Page.Resources section.  And yes, you’ll need both those closing “}” at the end, one for the Binding and one for the StaticResource, and since the Converter is INSIDE with the Binding, you need both nested.  Now, the astute reader will see the StaticResource has a lower case “g” and not the uppercase, in other words it’s NOT pointing to the public class we first declared.  Nope, and you’re correct!  It IS pointing to the Page.Resource x:Key which is like an instance of a class.  It helps me to think of that Page.Resources like “instantiating an object” just like you would do in a class, but you’re doing it in xaml, and since you gave it an x:Name you can now reference “that local variable” in your xaml.

Ok, so what’s your xaml look like when you’re all done?!


Ok, ok, I cheated a bit, I have a bit of extra stuff in there, I have another TextBlock with three Run blocks in there, I was trying out more binding to controls and wanted to share that with you too.  It’s all the same as before.

NOW, when you F5, you’ll be able to…..oh, you’ve already done that?  Cool!  Ya, now move the slider and you’ll see your letter grades climb from D to B to A+!!!!!!!!!!!  Great work, you passed! LOL 

There, NOW that you know a bit more about the mechanics of converters and you can link two controls together with data binding, it’s time to grab a coffee and get coding!


PS  The OTHER hidden agenda to this blog?  FINALLY finished uploading all my code to my project on CodePlex.  This concludes my use of SVN Server on my own server at home and using “the cloud” for my source code control.  For good (always available no matter what my servers status) and for bad (availability subject to CodePlex availability, and you might need TFS to download), I’ve trying to learn about TFS now!



Microsoft Virtual Academy: XAML Deep Dive for Windows and Windows Phone Apps Jump Start on CodePlex on CodePlex: DataBindingToAnotherControlValue

Location: Blogs Parent Separator TechTidBits

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Add Comment   Cancel 
Copyright 1999-2012 by   Terms Of Use  Privacy Statement