Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child elements in XAML

I'm just learning XAML so bear with me.

When you nest an element in XAML it seems like that element is set to the "Child" property of the parent UI.

However in the following code the child element is set to the value. That sort of makes sense - kinda.

However then Border Element below was set to the ControlTemplate, yet ControlTemplate has no Child element, so can someone tell me what exactly is the relationship between the Border and ControlTemplate below? May be you could re-write this snippet in c# as an explanation.

 <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="dtp:PickerSelectorItem">

                <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >

                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="Picker">
                            <VisualState x:Name="Focused">
                                <Storyboard>
               <!-- There is more code but snipped for irrelevance-->

Also how does the XAML compiler makes sense of what the child element actually does? Ie, how does it know that the child element should be set to the "Child" property, whereas other times it'd be set to the "Value" property as seen above.

like image 520
Alwyn Avatar asked Dec 12 '25 22:12

Alwyn


2 Answers

The XAML parser uses the ContentPropertyAttribute to determine how to handle child xaml elements. For example, if you look at the following two base controls you'll see how their usage is:

ContentControl:

[ContentPropertyAttribute("Content")]
public class ContentControl : Control, IAddChild { ... }

ItemsControl:

[ContentPropertyAttribute("Items")]
public class ItemsControl : Control, IAddChild, IContainItemStorage { ... }

It used to be that you would implement the IAddChild interface, but that is obsolete now. Also, the xaml parsing engine can recognize if your "content" property is pointing to a single object or a collection of objects. Basically, if you want to create your own custom control, make sure to use the correct attribute to control how your child(ren) are handled.

like image 152
myermian Avatar answered Dec 16 '25 15:12

myermian


The XAML parser knows which property to assign the inner XAML to according to the parent object type. For example, nesting XAML under a ContentControl will call parentContentControl.Content = child, while for ItemsControl it will add the children to the Items collection: parentItemsControl.Items.Add(child).

I guess the same is true for FrameworkTemplate objects (which ControlTemplate derives from), and child controls for these types are assigned to the VisualTree property.

like image 42
Adi Lester Avatar answered Dec 16 '25 17:12

Adi Lester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!