Child elements in XAML

2019-07-20 19:38发布

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.

3条回答
爷、活的狠高调
2楼-- · 2019-07-20 19:59

In your question, ControlTemplate uses FrameElementFactory to construct the controls defined on XAML and builds the visual tree which is finally assigned to ControlTemplate's VisualTree property.

查看更多
贪生不怕死
3楼-- · 2019-07-20 20:02

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.

查看更多
Rolldiameter
4楼-- · 2019-07-20 20:06

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.

查看更多
登录 后发表回答