• 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的功能,因此应该效率还能保证。但是我对此持怀疑态度。没有做过具体的测试,就不好说了。

  • 相关阅读:
    compilation debug= true targetframework= 4.0 / configuration error
    Using Temp table in SSIS package
    Using an Excel Destination in SSIS with x64
    SQL Server 中的两个查询级别的Hint NOLOCK和ROWLOCK
    SQL Server中的timeout设置
    Global.asax 转
    VC++动态链接库编程之MFC规则DLL
    堆栈详解(数据与内存中的存储方式) .
    [C++]拷贝构造函数和赋值运算符重载
    #ifdef __cplusplus extern "C" { #endif”的定义的含义 .
  • 原文地址:https://www.cnblogs.com/Cajon/p/184264.html
Copyright © 2020-2023  润新知