WPF中的Attached Property
Attached Property是Dependency Property的一種特殊形式,它是用DependencyProperty.RegisterAttached方法注冊的,可以被有效地添加到任何繼承自DependencyObject的對象中,所以被稱為Attached Property。一開始,這可能聽起來很奇怪,但這種機制在WPF中有很多種應用。
首先,我們先看看Attached Property的定義,以TextElement的FontSizeProperty為例:
public static readonly DependencyProperty FontSizeProperty;
FontSizeProperty = DependencyProperty.RegisterAttached(
??? "FontSize", typeof(double), typeof(TextElement), new FrameworkPropertyMetadata(
??? SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.Inherits |
??? FrameworkPropertyMetadataOptions.AffectsRender |
??? FrameworkPropertyMetadataOptions.AffectsMeasure),
??? new ValidateValueCallback(IsValidFontSize));
Attached Property的注冊和Dependency Property很相似,區別在于是用RegisterAttached還是用Register方法注冊。
對Attached Property的訪問,通過Static函數來實現。
public static double GetFontSize(DependencyObject element)
{
??? element.GetValue(FontSizeProperty);
}
public static void SetFontSize(DependencyObject element, double value)
{
??? element.SetValue(FontSizeProperty, value);
}
一般來說,Attached Property不會使用.NET屬性包裝器進行包裝。而且,實現Attached Property的類,并未調用自己的SetValue/GetValue方法,因此,實現Attached Property的類不需要繼承自DependencyObject。
下面的示例顯示在XAML中設置Attached Property:
<StackPanel TextElement.FontSize="30">
??? <Button Content="I'm a Button!"/>
</StackPanel>
StackPanel自己沒有任何與字體有關的屬性,如果要在StackPanel上設置字體大小,那么需要使用TextElement的FontSize Attached Property。當XAML解析器或編譯器遇到TextElement.FontSize這樣的語法時,它會去調用TextElement(Attached Property提供者)的SetFontSize函數,這樣它們才能設置相應的屬性值。另外,與普通的Dependency Property一樣,這些GetXXX和SetXXX方法只能調用SetValue/GetValue方法,不能挪作他用。
接下來,我們說說Attached Property的用途。
Attached Property屬性的一個用途是允許不同的子元素為實際在父元素中定義的屬性指定唯一值。此方案的一個具體應用是讓子元素通知父元素它們將如何在用戶界面 (UI) 中呈現。派生自Panel的各種類定義了一些Attached Property,用來把它們添加到子元素上來控制它們的擺放。通過這種方式,每個Panel可以把自定義行為給任何一個子元素,而不需要所有的子元素都具有自己的相關屬性集。
Attached Property屬性的另一個用途是可以作為一種擴展機制。即可以用Attached Property高效地向密封類的實例添加自定義數據。另外,Attached Property是Dependency Property,因此,可以把任何一個Dependency Property作為一個Attached Property。如果對實例進行了擴展,則SetValue設定的值是儲存在實例中的,可以通過GetValue獲得。總結
以上是生活随笔為你收集整理的WPF中的Attached Property的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么样的计算机书才是市场需要的——200
- 下一篇: NHibernate Step by S