WPF学习笔记3: Xaml之Property Element

是一种与基本 XML 语法稍有偏离的语法。不将 Property 指定为元素标记中的一个 Attribute,而是使用元素的开始标记指定格式为elementTypeName.propertyName 的Property,再指定属性 Property值,然后结束属性元素。
一般用于设置:
1. 该 Property Type 内容较为复杂
2. 该 Property是Collection

---------------------------------------------------------------------------------------------
具体语法
1. 以左尖括号 (<) 开头,其后紧跟包含属性元素语法的类或结构的类型名称。类型名称后面紧跟一个
点 (.),再后面是必须在指定类型的成员表中存在的属性名,最后面是一个右尖括号 (>)。
2. 要赋给属性的值包含在相应的属性元素中。
3. 通常,值作为一个或多个对象元素提供,因为将对象指定为值正是属性元素语法应当实现的方案。
4. 最后,必须提供一个等效的结束标记来指定同一个 elementTypeName.propertyName 组合,并与其他元素标记对形成正确的嵌套和平衡。

Sample1:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="1">First item</MenuItem>
      <MenuItem Header="2">Second item</MenuItem>
    </ContextMenu>
  </Button.ContextMenu>
  Right-click me!
</Button>

Sample2:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Button.Background>
    <SolidColorBrush Color="LightGreen" />
  </Button.Background>
  Click me
</Button>

Sample3:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
VerticalAlignment="Center" HorizontalAlignment="Center">
  <Button.Background>
    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
      <LinearGradientBrush.GradientStops>
        <GradientStop Offset="0" Color="#800" />
        <GradientStop Offset="0.35" Color="Red" />
        <GradientStop Offset="1" Color="#500" />
      </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>
  </Button.Background>
  Nested Element
</Button>

Sample3对应的C#代码

Button b = new Button( );
b.VerticalAlignment 
= VerticalAlignment.Center;
b.HorizontalAlignment 
= HorizontalAlignment.Center;
LinearGradientBrush brush 
= new LinearGradientBrush( );
brush.StartPoint 
= new Point(0,0);
brush.EndPoint 
= new Point(0,1);
GradientStop gs 
= new GradientStop( );
gs.Offset 
= 0;
gs.Color 
= Color.FromRgb(0x8000);
brush.GradientStops.Add(gs);
gs 
= new GradientStop( );
gs.Offset 
= 0.35;
gs.Color 
= Colors.Red;
brush.GradientStops.Add(gs);
gs 
= new GradientStop( );
gs.Offset 
= 0.35;
gs.Color 
= Color.FromRgb(0x5000);
brush.GradientStops.Add(gs);
b.Background 
= brush;
b.Content 
= "Click me";



---------------------------------------------------------------------------------------------
集合类型的属性元素语法
XAML 规范要求所实现的 XAML 处理器能够标识值类型是集合的属性。WPF 实现基于托管代码,它的

XAML 处理器通过下列操作之一来标识集合类型:
1. 实现 IList。
2. 实现 IDictionary。
3. 从 Array 派生(有关 XAML 中数组的更多信息,请参见 x:Array 标记扩展)。

posted @ 2008-02-25 12:31  Alen在西安  阅读(717)  评论(0编辑  收藏  举报