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/
轉載時須註明本文的詳細連結,否則作者將保留追究其法律責任。