This week I was going through StackOverflow, looking for anything I could help with and cam across someone asking about how to bind to an attribute of a class member in XAML. I wrote a small example IValueConverter class they could use to accomplish the task which was the only way I knew of that it could be done. Then, another poster (H.B.) solved the task using something I’d never heard of before…the MarkupExtension class.
Using the example H.B. gave, creating a class to display the DisplayName attribute of a property, you can see that this approach gets the job done just as well as a converter, but to me, it looks like it solves the problem in a much more direct way than a converter. The converters are generally used to convert a value from one Type to another Type, for instance, from a boolean to a value of System.Windows.Visibility or from a Color to a Brush.
To create a MarkupExtension class, you derive from the abstract MarkupExtension class. There is one method to override, called ProvideValue. A default constructor is required unless you intend to only support attribute usages of the class. If you want to support arguments in the usage, might also need to define additional constructors to match the settable properties.
Attached is a sample WPF application with code that implements the MarkupExtension and IValueConverters I’ve mentioned in this short write-up.
by