A user asked:
Is there a generic way of assigning a property a value, somewhat like you could do through XAML?
For example, if I specify the following code:
<Glyphs Fill=”#000000”>
How would I create a Fill property with value “#000000” through code? Note that I don’t want to create a new Glyphs object, but simply a Fill property.
The way that XAML works for that element is the following:
1) Creates a Glyphs object.
2) Determines the type of Fill is Brush.
3) Looks at the Brush type for the appropriate TypeConverter.
4) Uses the BrushConverter to convert to a Brush from the “#000000“ string.
BAML details
When you have compiled Xaml, we build a Baml file. When storing the attribute value in the Baml file, we check to see if the Brush type support IBamlSerialize. If so, it can store a more compact representation of the value than a string. At runtime, while loading the Baml, we use IBamlSerialize to convert the persisted version into an object. Some more XAML/BAML details are in my January post.
So how do you do this in Code:
Generally, you don’t want to use a TypeConverter if you are writing code for this.
<Update2>
Here is the code to use the TypeConverter, if you wanted to do that:
At first I had the totally generic code in here (see my first comment for it...)
Should have shown:
g1.Fill = BrushConverter.ConvertFromString(“Black“); //code isn't bad, but perf isn't optimal
</Update2>
This would be most efficient:
Glyphs g1 = new Glyphs();
g1.Fill = Brushes.Black; //Black is a static field on Brushes that is a SolidColorBrush with a Color of black, I believe…
Since you said you didn’t want to create a Glyphs object, you could do this:
<Glyphs ID=”g1”>
And in code (perhaps the Loaded event on the root element), you could then
g1.Fill = Brushes.Black;
Is there a Generic way of doing this?
No. Sorry, not yet.
I think this will be a common theme that we hear from “markup-oriented” developers. We could add a method to support the ability to use a string more easily in code. However, it would be nicer if CLR languages could provide Tool or Tool & Language support for people who think in strings, but don’t want to pay the cost for it at runtime.
HTML is:
-
easier to figure out how to set values in code, since you just use a string.
-
more troublesome to figure out if you have the right value...since bad values are often ignored.
-
when it does error, it waits until runtime (often on your users machine.)
What is on tap with WinFX?
I hope we can make development with WinFX friendlier to markup-oriented developers - like me.
Is our message:
“strong typing is good for you“
or:
“ok, we can make it easy and give you the benefits of strong typing“