一个动态属性(animation)的例子:
Rectangle拥有一个从属属性“Opacity”,例子中使用DoubleAnimation实现Rectangle的淡入淡出效果。
<
Page
xmlns
="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x
="http://schemas.microsoft.com/winfx/xaml/2005"
>
< StackPanel Margin ="30" >
<!-- The rectangle to animate. -->
< Rectangle Name ="myAnimatedRectangle"
Width ="100" Height ="100"
Fill ="Blue" />
</ StackPanel >
< Page .Storyboards >
<!-- Animates the opacity of the rectangle from 1.0 to 0.0 over five seconds. -->
< SetterTimeline TargetName ="myAnimatedRectangle" Path ="(Rectangle.Opacity)" >
< DoubleAnimation From ="1.0" To ="0.0" Duration ="0:0:5" AutoReverse ="True" RepeatBehavior ="Forever" />
</ SetterTimeline >
</ Page.Storyboards >
</ Page >
< StackPanel Margin ="30" >
<!-- The rectangle to animate. -->
< Rectangle Name ="myAnimatedRectangle"
Width ="100" Height ="100"
Fill ="Blue" />
</ StackPanel >
< Page .Storyboards >
<!-- Animates the opacity of the rectangle from 1.0 to 0.0 over five seconds. -->
< SetterTimeline TargetName ="myAnimatedRectangle" Path ="(Rectangle.Opacity)" >
< DoubleAnimation From ="1.0" To ="0.0" Duration ="0:0:5" AutoReverse ="True" RepeatBehavior ="Forever" />
</ SetterTimeline >
</ Page.Storyboards >
</ Page >
可以直接将上面的例子复制到XAMLPad看效果。
从属属性
声明一个从属属性需要先为类型定义一个属性,然后使用如下的语法注册这个从属属性。
public
static
readonly
DependencyProperty CounterProperty
=
DependencyProperty.Register(
" PropertyName " , // 属性名
typeof ( int ), // 属性的类型
typeof (MyButtonSimple), // 属性所在的类型
new PropertyMetadata( 0 ) // 属性的默认值
);
DependencyProperty.Register(
" PropertyName " , // 属性名
typeof ( int ), // 属性的类型
typeof (MyButtonSimple), // 属性所在的类型
new PropertyMetadata( 0 ) // 属性的默认值
);
注册后,就可以使用XAML来访问这些属性了。于是,就可以使用Style或者Trigger来修改这些属性或者进行数据绑定了。
附加属性
附加属性看起来有点像.NET下的ToolTip组件的实现方式,只是提供了XAML的支持。所谓的附加属性,就是实现在另外一个类型中的属性。
例如:我们可以利用下面的代码将我们自定义的一个附加属性添加到系统类上而不需要建立一个新的继承层次。
<
Button
Name
="mybtn3"
custom:CustomAttachedPropertyClass.TheProperty
="3"
/>
所需要的,就是使用如下的代码声明一个附加属性类型。
public
class
CustomAttachedPropertyClass
{
public static readonly DependencyProperty ThePropertyProperty =
DependencyProperty.RegisterAttached(
"TheProperty",
typeof(int),
typeof(CustomAttachedPropertyClass),
new PropertyMetadata(0)
);
public static void SetTheProperty(DependencyObject d, int value)
{
d.SetValue(ThePropertyProperty, value);
}
public static int GetTheProperty(DependencyObject d)
{
return (int)d.GetValue(ThePropertyProperty);
}
}
{
public static readonly DependencyProperty ThePropertyProperty =
DependencyProperty.RegisterAttached(
"TheProperty",
typeof(int),
typeof(CustomAttachedPropertyClass),
new PropertyMetadata(0)
);
public static void SetTheProperty(DependencyObject d, int value)
{
d.SetValue(ThePropertyProperty, value);
}
public static int GetTheProperty(DependencyObject d)
{
return (int)d.GetValue(ThePropertyProperty);
}
}
据说在Avalon中,为从属属性和附加属性提供了Cache的功能,因此应该效率还能保证。但是我对此持怀疑态度。没有做过具体的测试,就不好说了。