views:

273

answers:

1

I'm trying to set the width property of one of my controls to a qualifiedDouble,
as described here on MSDN.
(Scroll down to the "XAML Values" section to see MSDN's info on the use of a qualifiedDouble)

However, I want to know how to achieve this in the code-behind, rather than XAML. The UserControls I am creating do not have XAML attached to them, for inheritance purposes. So I have to perform all XAML operations manually, using whatever I can in C#.

Does anyone know how qualifiedDouble is achieved in the code-behind?

+2  A: 

What coincidence, I had to do this earlier today. The qualified doubles end up going through a factor conversion based on the unit you give it, but as part of LengthConverter.

LengthConverter lc = new LengthConverter();
string qualifiedDouble = "10pt";

double converted = lc.ConvertFrom( qualifiedDouble );

Alternate:

double original = 10.0;
double converted = original * 1.333333333; // px-to-pt conversion

This will transform "10pt" to 13.3333333, for example. You could also use the conversion factors the article supplies, but I prefer to use the above since the factors are built into the class.

Edited: In response to comment about strings...

String conversion makes perfect sense for what it was intended for. They use XAML because it is so much easier to express some things in XAML than in C# or VB. In XAML, all the values are strings, so you have TypeConverters automatically selected to convert the string to the target type. FontSizeConverter for example, calls an internal static method on LengthConverter. (You could also instantiate FontSizeConverter instead.) There are also converters for GridLengths like "4*" and Widths like "Auto". Or, like I said, you can create your own class to convert without strings.

This article recommends, for code-behind, to use the factor directly, so I supplied an alternate example above.

Joel B Fant
This makes sense. Although I'm a little disappointed that it's a runtime string conversion. Microsoft is becoming too dependent on strings, I think.
Giffyguy
Ah, that DOES makes sense. They want you to perform the conversion yourself if you have any beefs with strings. My particular problem with string-conversion is performance - and there'll be tens of thousands of these conversions happening all over the place in my app, and it can't be allowed to lag. So the obvious solution from microsoft is to do it myself in the way that will benefit me most.
Giffyguy