日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

WPF中的Attached Property

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

Attached PropertyDependency Property的一種特殊形式,它是用DependencyProperty.RegisterAttached方法注冊(cè)的,可以被有效地添加到任何繼承自DependencyObject的對(duì)象中,所以被稱為Attached Property。一開始,這可能聽起來很奇怪,但這種機(jī)制在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的注冊(cè)和Dependency Property很相似,區(qū)別在于是用RegisterAttached還是用Register方法注冊(cè)。

對(duì)Attached Property的訪問,通過Static函數(shù)來實(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不會(huì)使用.NET屬性包裝器進(jìn)行包裝。而且,實(shí)現(xiàn)Attached Property的類,并未調(diào)用自己的SetValue/GetValue方法,因此,實(shí)現(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。當(dāng)XAML解析器或編譯器遇到TextElement.FontSize這樣的語(yǔ)法時(shí),它會(huì)去調(diào)用TextElementAttached Property提供者)的SetFontSize函數(shù),這樣它們才能設(shè)置相應(yīng)的屬性值。另外,與普通的Dependency Property一樣,這些GetXXXSetXXX方法只能調(diào)用SetValue/GetValue方法,不能挪作他用。

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

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

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

總結(jié)

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

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