How do you set the FrameworkElement.Width property to the value of a qualifiedDouble, in the code-behind?

本小妞迷上赌 提交于 2019-12-07 17:56:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1279102/how-do-you-set-the-frameworkelement-width-property-to-the-value-of-a-qualifieddo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!