DataBinding to Custom Properties

In a recent three part mini-series I showed how to create a Xaml program from scratch. In the third part of the series I showed how the values are computed for display, but I glossed over how the display value is bound to the display control itself. Let’s focus on that for a moment in what I guess is now part 4 of the three part series.

As noted in part 3, we begin by looking at the DisplayNumber property. When all is said and done, this property will have the value that should be displayed in the output window. Here’s the Xaml for the output window:

Notice that the TextBlock is wrapped in a Border. TextBlocks cannot set the background color, but Borders can. In our case, we’re going to want to adjust some of the properties of the TextBlock. The easiest way to do this is to open the project in Blend and click on the TextBlock to update its properties.

Set the font-size to 30 point, set the font to Segoe WP Semibold and click Bold as well, and use the paragraph tab to align to the right, and VerticalAlignment to center. Finally, click on the Foreground color and change it from white (255,255,255) to black (0,0,0).

Now it is time to bind the display to the DisplayNumber property. Click on the Advanced properties peg next to the Text (as shown in the illustration) and then click on DataBinding. This will open the Create Data Binding dialog box. Click on the Data Context tab, but note that there are no designated fields.

We know, however, that the property we want is called DisplayNumber. Check the Use a custom path expression checkbox, and fill in the name of the DisplayNumber property.

This creates a binding between the TextBlock and the DisplayNumber property. It is worth examining the Xaml (either in Blend or back in Visual Studio).

What you end up with in the Xaml is a straight forward Binding like any other. In fact, in this case you might have decided just to hand-code the binding.

In any case, as the DisplayNumber is updated (by clicking keys on the calculator) the value in the display is updated via the binding.

About Jesse Liberty

Jesse Liberty is a Senior Consultant with Wintellect, with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight & LinkedIn Learning courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.