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

来源:互联网 发布:office办公软件培训班 编辑:程序博客网 时间:2024/04/29 10:44

子对象元素

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

 

内容属性

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

1:简单内容(文本)

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

Content="OK" />

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

<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:复杂内容的简略写法(内容属性类型子元素,作为ButtonContent属性)

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

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

</Button>

    可用作内容属性类型的属性名称并不是必须叫做“Content”,实际上如ComboBoxListBoxTabControl控件是使用它们的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);

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

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

<ListBoxItem Content="Item 1" />

<ListBoxItem Content="Item 1" />

</ListBox>

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

 
原创粉丝点击