DependencyProperty Converter On UserControl
I am working on a user control that has some dependency properties, namely;
public static readonly DependencyProperty TitleWidthProperty = DependencyProperty.Register("TitleWidth", typeof(double), typeof(FormList));
OK, great, so when using it in XAML I can easily bind to said property using a normal 'double' value like so;
<local:FormList TitleWidth="100">
Awesome! 开发者_开发技巧Just what I want, works like a dream. However, I want to try something a bit more clever and say; (obviously some other code will determine the width)
<local:FormList TitleWidth="Auto">
But no matter what I do with the dependency property, all I ever get is a FormatException in the designer because "Auto" is a string and not a double. I have tried all sorts of combinations of PropertyMetadata, ValueCorercion and ValidateValue callbacks to no avail. I know that there is a way to do this because it works for some of the built in controls, for example;
<!-- 'Red is a color and not a 'Brush' so there is some conversion happening here.-->
<Border Background="Red"/>
Any ideas, or info on where to get more information ?
There is default value-conversion going on:
The string value contained within the opening and closing quotation marks is processed by a XAML processor. For properties, the default processing behavior is determined by the type of the underlying CLR property.
The attribute value is filled by one of the following, using this processing order:
If the XAML processor encounters a curly brace, or an object element that derives from MarkupExtension, then the referenced markup extension is evaluated first rather than processing the value as a string, and the object returned by the markup extension is used as the value. In many cases the object returned by a markup extension will be a reference to an existing object, or an expression that defers evaluation until run time, and is not a newly instantiated object.
If the property is declared with an attributed TypeConverter, or the value type of that property is declared with an attributed TypeConverter, the string value of the attribute is submitted to the type converter as a conversion input, and the converter will return a new object instance.
If there is no TypeConverter, a direct conversion to the property type is attempted. This final level is a direct conversion at the parser-native value between XAML language primitive types, or a check for the names of named constants in an enumeration (the parser then accesses the matching values).
From MSDN
You can create a TypeConverter that should handle the string the way you want. (e.g. as with some WPF controls turn Auto
into double.NaN
)
Instead of double
, you need a type that supports the concept of an automatic size, such as GridLength
. Then, of course, your control needs to pass that value onto something that knows what to do with it (such as a Grid
) or you need to code that logic yourself.
精彩评论