WPF整理-爲User Control添加依賴屬性

WPF整理-爲User Control添加依賴屬性

依賴屬性

".NET properties are nothing more than syntactic sugar over set and get methods."

我們知道.NET的屬性只不過是get/set方法的語法糖衣。

"Dependency properties are the workhorse of WPF. This infrastructure provides for many of WPF's features, such as data binding, animations, and visual inheritance. In fact, most of the various element properties are Dependency Properties. Sometimes we need to create such properties for our own controls or windows."

依賴屬性這個基礎架構爲我們提供了實現WPF諸多特性的基礎,如數據綁定、動畫等。

DependencyObject和DependencyPorperty兩個類是WPF屬性系統的核心。DependencyObject是WPF系統中相當底層的一個基類,如下:

從這顆繼承樹可以看出,WPF的所有UI控件都是依賴對象。WPF的類庫在設計時充分利用了依賴屬性的優勢,UI空間的絕大多數屬性都已經依賴化了。

有些時候,我們需要爲我們自定義的類或控件等添加依賴屬性。

DebugLZQ前面的博文:WPF 自定義依賴屬性 介紹瞭如何爲自定義的類添加依賴屬性;這篇博文以前面的博文爲基礎,介紹如何爲User Control添加Dependency Property。

爲User Control添加依賴屬性

1.首先定義一個名爲SimpleControl的UserControl;在SimpleControl.xaml.cs中鍵入"propdp"

連按2次Tab,修改依賴屬性名爲YearPublishedProperty,屬性包裝名爲YearPublished,默認值爲2013。最終如下:

複製代碼
public int YearPublished
{
    get { return (int)GetValue(YearPublishedProperty); }
    set { SetValue(YearPublishedProperty, value); }
}
        
public static readonly DependencyProperty YearPublishedProperty =
   DependencyProperty.Register("YearPublished", typeof(int), typeof(SimpleControl), new PropertyMetadata(2013)); 
複製代碼

2.爲了能在XAML中使用,添加這個映射

<Window x:Class="CreatingADependencyProperty.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CreatingADependencyProperty" 

我們用Binding使用如下:

複製代碼
    <StackPanel>
        <local:SimpleControl x:Name="_simple"/>
        <TextBlock Text="{Binding YearPublished,ElementName=_simple}" FontSize="30"/>
        <Button Content="Change Value" FontSize="20" Click="OnChangeValue"/>
    </StackPanel>
複製代碼

Click事件如下

private void OnChangeValue(object sender, RoutedEventArgs e)
{
     _simple.YearPublished++;
}

程序運行如下:

點擊幾次button

 

發佈了2 篇原創文章 · 獲贊 40 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章