Silverlight--DependencyProperty 类(一)

      DependencyProperty在Silverlight中是一个很有用的类,DependencyProperty是为值表达式、数据绑定、动画和属性更改通知提供支持,比如通常我们希望当进行数据修改时,一个控件的属性与一个对象绑定,实现数据一致性,DependencyProperty就可以帮我们完成。
     首先我们了解一下DependencyProperty类方法,重要的方法有GetMetadata 方法 、Register 方法 、RegisterAttached 方法 。

Register 方法,它是使用指定属性名称、属性类型、所有者类型和属性元数据注册依赖项属性,它的语法是:

public static DependencyProperty Register(
string name,
Type propertyType,
Type ownerType,
PropertyMetadata typeMetadata
)

      它的参数name指的是要注册的依赖项对象的名称,propertyType是指属性的类型,ownerType是正在注册依赖项对象的所有者类型,还有typeMetadata指的是属性元数据实例,如果不需要依赖项属性的属性元数据,可以将 typeMetadata 指定为 null。

下面看一个示例,在Silverligh中我们自定义用户控件就可以使用DependencyProperty实现数据绑定。

首先在一个项目中新建一个用户控件,画一个按钮:

Xaml Code:

<grid x:Name="LayoutRoot">
<rectangle x:Name="rectangle" HorizontalAlignment="Left" Height="25" Margin="8,8,0,0" VerticalAlignment="Top" Width="100" RadiusY="8" RadiusX="8">
</rectangle><rectangle .Fill>
<lineargradientbrush EndPoint="0.516,1.18" StartPoint="0.509,-0.083">
<gradientstop Color="White" Offset="0"/>
<gradientstop Color="#FF131614" Offset="0.619"/>
</lineargradientbrush>
</rectangle>
<textblock x:Name="mytext" HorizontalAlignment="Left" Height="15" Margin="24,13,0,0" TextWrapping="Wrap" Text="{Binding GreenButtonsText, ElementName=userControl}" VerticalAlignment="Top" Width="67" TextAlignment="Center"/>
</grid>

  这时这个自定义控件上按钮文本是不能被修改的,我们无法找的这个属性,需要使用DependencyProperty。下面我在它的后置代码中添加如下代码:

 1  public static readonly DependencyProperty ButtonsText =DependencyProperty.Register("MyButtonsText", typeof(String),typeof(buttonDemo), null);
2
3 public String MyButtonsText
4 {
5 get {
6 return (String)GetValue(ButtonsText);
7 }
8 set {
9 SetValue(ButtonsText, value);
10 }
11 }

  下面我们使用Microsoft Expression Blend 4,将会查看到MyButtonsText属性。


      最后就是要对TextBlock的Text属性进行数据绑定。

     这样它就与普通按钮一样,修改MyButtonsText属性就可以更改按钮上的文本。好了,就到这里了。

更多内容访问:http://flute.vacau.com/

转载时须注明本文的详细链接,否则作者将保留追究其法律责任。

posted @ 2011-08-16 20:33  flute  阅读(1392)  评论(1编辑  收藏  举报