Avalon学习笔记(二)——从属属性 和 附加属性

在Avalon设计模型中引入了两个新的概念——从属属性(Dependency Properties)和附加属性(Attached Property)通过它们,我们可以实现风格化(Styling),数据绑定,默认值,动态属性(animation)等等一系列非常酷的功能。

一个动态属性(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>

可以直接将上面的例子复制到XAMLPad看效果。

从属属性

声明一个从属属性需要先为类型定义一个属性,然后使用如下的语法注册这个从属属性。
public static readonly DependencyProperty CounterProperty = 
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);
    }

}

据说在Avalon中,为从属属性和附加属性提供了Cache的功能,因此应该效率还能保证。但是我对此持怀疑态度。没有做过具体的测试,就不好说了。

posted @ 2005-07-01 00:00 Colin Han 阅读(1640) 评论(1)  编辑 收藏 网摘 所属分类: WPF

  回复  引用  查看    
#1楼[楼主]2005-07-01 10:12 | Cajon's Blog      
使用C#实现动态Button的例子:

// Create and set the Button.
Button aButton = new Button();
aButton.Content = "A Button";


// Create the animation instance.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 75;
myDoubleAnimation.To = 300;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(5000));
myDoubleAnimation.AutoReverse = true;
myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

// Animate the Button's Width.
aButton.PersistentAnimations[Button.WidthProperty] = myDoubleAnimation;




发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 184264




相关文章:

相关链接: