Here is one link which describes what is markup extension and available markup extensions.
Markup extensions are very much useful to obtain a clean project.Things won't get mixed with each other.Xaml itself contains the lines which have the functionality.
Consider the scenario where we need to display all properties of given class in a listbox.We normally write C# or VB code to get PropertyInfo objects and return the same.This code normally resides in presentation files itself.
Here comes the need for markup extension.We can write our own extension by inheriting from the MarkUpExtension class.
Steps to Create a custom markup extension
- Create a class which derives from MarkupExtension.The naming convention is that the class name should ends with 'Extension' .Eg:TypeDescriptorExtension
- If we need to accept a default parameter with extension write a constructor
- Add other properties as well.
- Override ProvideValue Method and return the appropriate value after processing.
Eg: Creating custom markup extension to list Properties and methods of a Class
The PropertyDescriptorExtension class is derived from Markupextension and it accepts an object Type as default parameter.So the constructor is written with a parameter of type 'Type'.
public class TypeDescriptorExtension:MarkupExtension
{
public TypeDescriptorExtension( Type type):this()
{
Type = type;
}
}
The other properties are IncludeProperties and InCludeMethods which are boolean to indicate whether the out put list should include Properties and Methods respectively.IncludeProperties is true by default.
Now override the ProvideValue method.Get the properties and methods collection based on the properties using Reflection and return as well.
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (Type == null)
{
throw new InvalidOperationException("The Class must be specified.");
}
List<string> items = new List<string>();
if (IncludeProperties)
{
foreach (PropertyInfo item in Type.GetProperties())
{
items.Add(item.ToString());
}
}
if (IncludeMethods)
{
foreach (MethodInfo info in Type.GetMethods())
{
items.Add(info.ToString());
}
}
return items;
}
Using the TypeDescriptorExtension
Normal, which displays only properties
<ListBox ItemsSource="{Binding Source={local:TypeDescriptor {x:Type Button}}}" />
Displays methods only
<ListBox ItemsSource="{Binding Source={local:TypeDescriptor {x:Type Button},IncludeMethods=True,IncludeProperties=False}}" />
Sample is available here.
No comments:
Post a Comment