When you create a new user control item in VS, it generates the following line of code. This API as I have said in this post, creates an object tree from the Xaml passed in string format.
_progressBarRoot = InitializeFromXaml(_progressBarLook) as Canvas;
This is essentially to make things easy for control developers. There are few things that need to happen when you are creating a object tree from XAML in string format in the custom control scenario…
- Create object tree that represents the XAML in string format
- object tree need to be created with namescoping turned on so that you can instantiate same control multiple times on a given page and names of individual element would not conflict
- Three tree that is created should become child of Control class
- Event handlers that are specified in the XAML should be hooked. Parser should look for those event handler in the class instead of root element of the XAML as it typically does for the page XAML.
<Canvas xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="70" Height="70" MouseEnter="_rootCanvas_MouseEnter" >
then ‘_rootCanvas_MouseEnter is implemented on custom class that inherits from Control class rather than Canvas at the root.
If we were to use the XamlReader.Load instead of InitializeFromXaml then…
- You would need to inherit from Canvas
- you will need to call XamlReader.Load (string, bool) with namescoping turned on
- You need to add the tree returned by XamlReader to Canvas.Children collection
- Hook up all the event handler in code using language specific syntax.
#1 is not the correct model because Canvas has multiple properties that Control class does not need. E.g. it has children property because it is designed to be a container for various element. Control, should have it a single child that holds the visual look of the control, Canvas has Top, Left dependency properties or background properties that are needed on Control. Once you decide to use Control as base class now you can not do #3 because Control does not Children property (or Child!). IntializeFromXaml automatically takes care of these things for you by adding the tree under the control internally.