XAML 中的子元素 [英] Child elements in XAML

查看:32
本文介绍了XAML 中的子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 XAML,所以请耐心等待.

I'm just learning XAML so bear with me.

当您在 XAML 中嵌套一个元素时,该元素似乎被设置为父 UI 的子"属性.

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.

但是下面的Border Element被设置为ControlTemplate,而ControlTemplate没有子元素,那么谁能告诉我下面的Border和ControlTemplate之间到底是什么关系?也许你可以用 c# 重写这个片段作为解释.

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-->

此外,XAML 编译器如何理解子元素的实际作用?即,它怎么知道子元素应该被设置为Child"属性,而其他时候它会被设置为Value"属性,如上所示.

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.

推荐答案

XAML 解析器使用 ContentPropertyAttribute 确定如何处理子 xaml 元素.例如,如果您查看以下两个基本控件,您将了解它们的用法:

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 { ... }

过去,您需要实施 IAddChild 接口,但现在已经过时了.此外,xaml 解析引擎可以识别您的内容"属性是指向单个对象还是对象集合.基本上,如果您想创建自己的自定义控件,请确保使用正确的属性来控制如何处理您的孩子.

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.

这篇关于XAML 中的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆