This example is from the wpf programming guide and some code is slightly adjusted.
In this example, the reflection mechanism is used to read all the classes inherited from the Control in the dataset, including the Control itself. After selecting the corresponding menu items, the corresponding Control is created in the form.
The file is automatically upgraded to a Xaml file.
Figure 1
Figure 2
Figure 3
The Code Section includes a ControlMenuItem type derived from MenuItem, which creates a menu containing all Control child types. The Header of each sub-menu item shows the Type name, and the Tag attribute stores the Type object of this Type.
Sample Code:
Code
Public class ControlMenuItem: MenuItem
{
Public ControlMenuItem ()
{
Var assembly = Assembly. GetAssembly (typeof (Control ));
Var aTypes = assembly. GetTypes ();
Var sortList = new SortedList <string, MenuItem> ();
Header = "Control ";
Tag = typeof (Control );
SortList. Add ("Control", this );
Foreach (var type in aTypes)
{
If (type. IsPublic &&
Type. IsSubclassOf (typeof (Control )))
{
SortList. Add (type. Name,
New MenuItem
{
Header = type. Name,
Tag = type
});
}
}
Foreach (var kvp in sortList)
{
If (kvp. Key = "Control") continue;
Var strParent = (Type) kvp. Value. Tag). BaseType. Name;
Var itemParent = sortList [strParent];
ItemParent. Items. Add (kvp. Value );
}
Foreach (var kvp in sortList)
{
Var type = (Type) kvp. Value. Tag;
If (type. IsAbstract & kvp. Value. Items. Count = 0)
Kvp. Value. IsEnabled = false;
Else
Kvp. Value. Items. Insert (0,
New MenuItem
{
Header = kvp. Value. Header as string,
Tag = type
});
}
}
}
All types derived from ContentControl use ContentPresenter objects to display their content. ContentPresenter is derived from FrameworkElement. You can include a ContentPresenter object in the visual tree of the template. The new approach is much better than the assumption that the content must be a string.
Any visually visible control defined by Wpf has set the period Template to ControlTemplate type. When you set the Template Property to your own ControlTemplate, you replace the original template.
Click to download the complete example