[笔记/简译]XAML揭秘(4)

子对象元素

    XAML 文件与 XML 文件类似,必须有一个根对象元素,自 然 XAML 也支持子对象元素。一个对象元素可以有三种类型的子元素:内容属性( content property )值、集合项( collection items )或可以被转换为父类的值

 

内容属性

    大多数 WPF 类设计了一个可以被设置为任意值的属 性,这个属性被称作 内容属性 Button Content 属性就是符合这种规则的设计, 如下四个等价的示例:

1 :简单内容(文本)

< Button xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation "

Content = " OK " />

2 :简单内容的简略写法 (内容属性类型子元素,作为 Button Content 属性)

< Button xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation " >

OK

</ Button >

3 :复杂内容(对象)

< Button xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation " >

< Button.Content >

< Rectangle Height = " 40 " Width = " 40 " Fill = " Black " />

</ Button.Content >

</ Button >

4 :复杂内容的简略写法(内容属性类型子元 素,作为 Button Content 属性)

< Button xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation " >

< Rectangle Height = " 40 " Width = " 40 " Fill = " Black " />

</ Button >

    可用作内容属性类型的属性名称并不是必须叫做 “Content” ,实际上如 ComboBox ListBox TabControl 控件是使用它们的 Items 属性作为内容属性的。

    WPF 中的 Button 类从 ButtonBase 类派生, ButtonBase 类又从 ContentControl 类派生,而 ContentControl 类使用其 Content 属性构造了 System.Windows.Markup.ContentPropertyAttribute 自定义特性,即对于所有的 ContentControl ,其 Content 属性将会作为它们的内容属性(子对象元 素)。同理, ComboBox 类间接从 ItemsControl 派生,其 Items 属性用于构造 ContentPropertyAttribute ,即其 Items 属性将会作为它的内容属性(子对象元素)。 由此可知,如果我们需要从已有控件继承,或从控件基类 Control 派生自定义的控件,需要注意 ContentPropertyAttribute 的作用。)

 

集合项

    XAML 允许我们添加两种支持索引的类型:列表( List )和字典( Dictionary )。

 

列表

    列表是任何实现了 System.Collections.IList 接口的集合,比如 System.Collections.ArrayList 或者许多由 WPF 定义的集合类。 下例向 ListBox 控件添加了两个项目,它的 Items 属性是 ItemCollection 类型的,该类型实现了 IList 接口:

例: XAML

< ListBox xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation " >

< ListBox.Items >

< ListBoxItem Content = " Item 1 " />

< ListBoxItem Content = " Item 1 " />

</ ListBox.Items >

</ ListBox >

    C#

System.Windows.Controls. ListBox listbox = new System.Windows.Controls. ListBox ();

System.Windows.Controls. ListBoxItem item1 =

new System.Windows.Controls. ListBoxItem ();

System.Windows.Controls. ListBoxItem item2 =

new System.Windows.Controls. ListBoxItem ();

item1.Content = "Item 1" ;

item2.Content = "Item 2" ;

listbox.Items.Add(item1);

listbox.Items.Add(item2);

    进一步,由于 ListBox Items 属性是其内容属性,因此,还可以简化上例:

< ListBox xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation " >

< ListBoxItem Content = " Item 1 " />

< ListBoxItem Content = " Item 1 " />

</ ListBox >

    上面的代码可以正常工作是因为 ListBox Items 属性(只读)被自动初始化为空( empty )集合对 象。如果集合属性一开始是 null (不明白) ,并且可以读 / 写,我们就必须显式地将集合项放入实例化这个集合的元素当中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值