日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

WPF中的Attached Property

發(fā)布時間:2025/3/20 asp.net 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 WPF中的Attached Property 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Attached PropertyDependency Property的一種特殊形式,它是用DependencyProperty.RegisterAttached方法注冊的,可以被有效地添加到任何繼承自DependencyObject的對象中,所以被稱為Attached Property。一開始,這可能聽起來很奇怪,但這種機制在WPF中有很多種應(yīng)用。

首先,我們先看看Attached Property的定義,以TextElementFontSizeProperty為例:

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很相似,區(qū)別在于是用RegisterAttached還是用Register方法注冊。

Attached Property的訪問,通過Static函數(shù)來實現(xiàn)。

public static double GetFontSize(DependencyObject element)

{

??? element.GetValue(FontSizeProperty);

}

public static void SetFontSize(DependencyObject element, double value)

{

??? element.SetValue(FontSizeProperty, value);

}

一般來說,Attached Property不會使用.NET屬性包裝器進行包裝。而且,實現(xiàn)Attached Property的類,并未調(diào)用自己的SetValue/GetValue方法,因此,實現(xiàn)Attached Property的類不需要繼承自DependencyObject

下面的示例顯示在XAML中設(shè)置Attached Property

<StackPanel TextElement.FontSize="30">

??? <Button Content="I'm a Button!"/>

</StackPanel>

StackPanel自己沒有任何與字體有關(guān)的屬性,如果要在StackPanel上設(shè)置字體大小,那么需要使用TextElementFontSize Attached Property。當XAML解析器或編譯器遇到TextElement.FontSize這樣的語法時,它會去調(diào)用TextElementAttached Property提供者)的SetFontSize函數(shù),這樣它們才能設(shè)置相應(yīng)的屬性值。另外,與普通的Dependency Property一樣,這些GetXXXSetXXX方法只能調(diào)用SetValue/GetValue方法,不能挪作他用。

接下來,我們說說Attached Property的用途。

Attached Property屬性的一個用途是允許不同的子元素為實際在父元素中定義的屬性指定唯一值。此方案的一個具體應(yīng)用是讓子元素通知父元素它們將如何在用戶界面 (UI) 中呈現(xiàn)。派生自Panel的各種類定義了一些Attached Property,用來把它們添加到子元素上來控制它們的擺放。通過這種方式,每個Panel可以把自定義行為給任何一個子元素,而不需要所有的子元素都具有自己的相關(guān)屬性集。

Attached Property屬性的另一個用途是可以作為一種擴展機制。即可以用Attached Property高效地向密封類的實例添加自定義數(shù)據(jù)。另外,Attached PropertyDependency Property,因此,可以把任何一個Dependency Property作為一個Attached Property。如果對實例進行了擴展,則SetValue設(shè)定的值是儲存在實例中的,可以通過GetValue獲得。

總結(jié)

以上是生活随笔為你收集整理的WPF中的Attached Property的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。